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.

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

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]]


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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