What is the best way to remake Hash in Ruby?

Is there an easy way to reassign the hash to ruby ​​as follows:

from

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

in

{"foo" => "bar"}

Preferably in such a way as to simplify this operation when repeating over an array of this type of hashes:

from

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

in

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

Thanks.

+3
source share
5 answers
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"}
+9
source

A modified version of the Vanson Samuel code does this. It is single line, but rather long.

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 would not say that this is prettier than the version of Guiche.

+3
source

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

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

, , - , Hash [] :

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

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

, :

[{ name: "foo", value: "bar" },{name: "foo2", value: "bar2"}].map{ |k| k.values }.to_h
0

Source: https://habr.com/ru/post/1707022/


All Articles