📜 ⬆️ ⬇️

Notes on Ruby. №1. [[: key,: value], [: key2 ,: value2]] -> {: key =>: value ,: key2 =>: value2}

I plan to start very short notes on ruby.

Sometimes we need to convert a structure of the form [[: key,: value], [: key2,: value2]] to
{: key =>: value,: key2 =>: value2}

Short solution:
')
Hash [[[: key,: value], [: key2,: value2]]]

Unfortunately, in ruby ​​1.8.6 does not work. In 1.8.7, the bug (?) Was fixed.

The usual solution is:

[[: key,: value], [: key2,: value2]]. inject ({}) {| hash, pair | hash [pair [0]] = pair [1]; hash}

Mega-short solution, and most importantly clear and works everywhere from Eugzol'a :

Hash [* [[: key,: value], [: key2,: value2]]. Flatten]

Source: https://habr.com/ru/post/30055/


All Articles