Arnold Roa
Arnold Roa

Reputation: 7718

Create a hash from a map result

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?

Upvotes: 1

Views: 184

Answers (3)

Arup Rakshit
Arup Rakshit

Reputation: 118271

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 }

Upvotes: 3

sawa
sawa

Reputation: 168101

results.inject({}){|h, r| h[r.other_model.key_name] = r.value; h}

This is more efficient than other answers that create an intermediate array and then convert it to a hash.

Upvotes: 0

Arnold Roa
Arnold Roa

Reputation: 7718

So far my best approach is this:

Hash[results.map{|r| [r.other_model.key_name, r.value] } ]

Upvotes: 1

Related Questions