What is the best way to convert an array to a hash in Ruby

Nathan Fritz picture Nathan Fritz · Sep 2, 2008 · Viewed 129.5k times · Source

In Ruby, given an array in one of the following forms...

[apple, 1, banana, 2]
[[apple, 1], [banana, 2]]

...what is the best way to convert this into a hash in the form of...

{apple => 1, banana => 2}

Answer

John Topley picture John Topley · Sep 2, 2008

Simply use Hash[*array_variable.flatten]

For example:

a1 = ['apple', 1, 'banana', 2]
h1 = Hash[*a1.flatten(1)]
puts "h1: #{h1.inspect}"

a2 = [['apple', 1], ['banana', 2]]
h2 = Hash[*a2.flatten(1)]
puts "h2: #{h2.inspect}"

Using Array#flatten(1) limits the recursion so Array keys and values work as expected.