🌞


Note that this blog post has been archived. Information may be out of date or incorrect.

Ruby 1.9- Array to Hash

If you google for “Array to Hash” then you will probably see this snippet close to the top of your search results, and it works pretty well too. However, since that snippet was posted, 6 years have passed, and with Ruby 1.9 it is a bit simpler now:

Ruby < 1.9:

a = [1, 2, 3].collect { |v| [v, v*2] } # => [ [1, 2], [2, 4], [3, 6] ]
Hash[*a.flatten]                       # => {1=>2, 2=>4, 3=>6} 

Ruby 1.9:

a = [1, 2, 3].collect { |v| [v, v*2] } # => [ [1, 2], [2, 4], [3, 6] ]
Hash[a]                                # => {1=>2, 2=>4, 3=>6} 

This is because Ruby 1.9 features a new form for Hash[ ]:

Hash[ [ [key, value], ... ] ] → new_hash

More info in the docs.