将哈希数组转换为以值作为键的单个哈希

Convert array of hashes to single hash with values as keys

给定一个散列源数组:

[{:country=>'england', :cost=>12.34}, {:country=>'scotland', :cost=>56.78}]

是否有一种简洁的 Ruby 单行代码将其转换为单个散列,其中原始散列中 :country 键的值(保证是唯一的)成为散列中的键新哈希?

{:england=>12.34, :scotland=>56.78}

这应该可以满足您的需求

countries.each_with_object({}) { |country, h| h[country[:country].to_sym] = country[:cost] }
 => {:england=>12.34, :scotland=>56.78}

另一种可能的解决方案是:

countries.map(&:values).to_h
 => {"england"=>12.34, "scotland"=>56.78}

您可以使用 Enumerable#inject:

countries.inject({}) { |hsh, element| hsh.merge!(element[:country].to_sym => element[:cost]) }
 => {:england=>12.34, :scotland=>56.78}

我们将累加器初始化为 {},然后迭代初始数组的每个元素并将新的格式化元素添加到累加器。

要补充的一点是,使用 hsh.mergehsh.merge! 会对输出产生相同的效果,因为 inject 会将累加器 hsh 设置为return 块中的值。但是,在内存使用方面使用 merge! 更好,因为 merge 将始终生成新的哈希,而 merge! 将对相同的现有哈希应用合并。