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

About these ads

3 thoughts on “Ruby – Convert Array into Hash

  1. Pingback: Rails – Retrieve a Hash from Model | Eureka!

  2. Suresh

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

    Reply

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s