Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有以下哈希数组:
a = [{:a => 1, :b => "x"}, {:a => 2, :b => "y"}]
我需要把它变成:
z={"x" => 1, "y" => 2}
或者:
z={1 => "x", 2 => "y"}
我可以以干净和实用的方式做到这一点吗?
像这样的东西:
Hash[a.map(&:values)] # => {1=>"x", 2=>"y"}
如果你想要另一种方式:
Hash[a.map(&:values).map(&:reverse)] # => {"x"=>1, "y"=>2}
结合@squiguy 的建议:
Hash[a.map(&:values)].invert