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
h = { “c” => 300, “a” => 100, “d” => 400, “c” => 300 }
h.to_a #=> [[“c”, 300], [“a”, 100], [“d”, 400]]
LikeLike
Hi Suresh, what do u want to share with us?
LikeLike