I need to create a hash using the key_name and value from a set of results.
It would be clear if I show you what I have:
results.map{|r| {r.other_model.key_name=>r.value} }
that is giving me this:
[{"api_token"=>"stes"}, {"Name"=>"nononono"}]
But I want this:
{"api_token"=>"stes", "Name"=>"nononono"}
What is the most beautiful way to do this on ruby?
Do as below using Hash::[]
Hash[results.map { |r| [r.other_model.key_name,r.value] } ]
In Ruby 2.1.0, we have Hash#to_h
results.map { |r| [r.other_model.key_name,r.value] }.to_h
or use Enumerable#each_with_object
results.each_with_object({}) { |r,h| h[ r.other_model.key_name ] = r.value }
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments