Ruby – Convert Array into Hash

I find a great tutorial about the inject method which is written by Jay Field @ Jay Fields’ Thoughts – Ruby: inject. One of the example is converting an array into hash.
array_to_hash.rb

hash = [[:first_name, 'Shane'], [:last_name, 'Harvie']].inject({}) do |result, element|
  result[element.first] = element.last
  result
end

puts hash

 

Run the above ruby by ruby array_to_hash.ruby. Then you got

 

Done =)

Reference: Jay Fields’ Thoughts – Ruby: inject

3 thoughts on “Ruby – Convert Array into Hash”

  1. h = { “c” => 300, “a” => 100, “d” => 400, “c” => 300 }
    h.to_a #=> [[“c”, 300], [“a”, 100], [“d”, 400]]

    Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.