在Ruby中重新映射Hash的最佳方法是什么?

Fre*_*röm 3 ruby hash remap

有一种简单的方法可以通过以下方式在ruby中重新映射哈希:

从:

{:name => "foo", :value => "bar"}
Run Code Online (Sandbox Code Playgroud)

至:

{"foo" => "bar"}
Run Code Online (Sandbox Code Playgroud)

优选地,在迭代这种类型的散列的数组的同时使得操作变得简单:

从:

[{:name => "foo", :value => "bar"}, {:name => "foo2", :value => "bar2"}]
Run Code Online (Sandbox Code Playgroud)

至:

{"foo" => "bar", "foo2" => "bar2"}
Run Code Online (Sandbox Code Playgroud)

谢谢.

Gis*_*shu 9

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"}
Run Code Online (Sandbox Code Playgroud)

  • 哈希值无序,因此您无法执行x.values [0]和x.values [1] (3认同)