Question

Is there a simple way of remapping a hash in ruby the following way:

from:

{:name => "foo", :value => "bar"}

to:

{"foo" => "bar"}

Preferably in a way that makes it simple to do this operation while iterating over an array of this type of hashes:

from:

[{:name => "foo", :value => "bar"}, {:name => "foo2", :value => "bar2"}]

to:

{"foo" => "bar", "foo2" => "bar2"}

Thanks.

Was it helpful?

Solution

arr = [ {:name=>"foo", :value=>"bar"}, {:name=>"foo2", :value=>"bar2"}]

result = {}
arr.each{|x| result[x[:name]] = x[:value]}

# result is now {"foo2"=>"bar2", "foo"=>"bar"}

OTHER TIPS

A modified version of Vanson Samuel's code does the intended. It's a one-liner, but quite a long one.

arr = [{:name=>"foo", :value=>"bar"}, {:name=>"foo2", :value=>"bar2"}]

arr.inject({}){|r,item| r.merge({item['name'] => item['value']})}

# result {"foo" => "bar", "foo2" => "bar2"}

I wouldn't say that it's prettier than Gishu's version, though.

As a general rule of thumb, if you have a hash of the form {:name => "foo", :value => "bar"}, you're usually better off with using a tuple of ["foo", "bar"].

arr = [["foo", "bar"], ["foo2", "bar2"]]
arr.inject({}) { |accu, (key, value)| accu[key] = value; accu }

I know this is old, but the neatest way to achieve this is to map the array of hashes to an array of tuples, then use Hash[] to build a hash from that, as follows:

arr = [{:name => "foo", :value => "bar"}, {:name => "foo2", :value => "bar2"}]
Hash[ array.map { |item| [ item[:name], item[:value] ] } ]

# => {"foo"=>"bar", "foo2"=>"bar2"}

a bit late but:

[{ name: "foo", value: "bar" },{name: "foo2", value: "bar2"}].map{ |k| k.values }.to_h
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top