在Ruby中加入哈希数组

我正在尝试使用公共密钥加入ruby中的多个哈希数组。 例如:

country_info = [ {country_id: "US", country_desc: "United States"}, {country_id: "AU", country_desc: "Australia"} ] country_stats = [ {country_id:"US", pageviews: 150}, {country_id:"AU", pageviews: 200} ] i_want = [ {country_id: "US", country_desc: "United States", pageviews:150}, {country_id: "AU", country_desc: "Australia", pageviews:200} ] 

这类似于Javascript中protovis的pv.nestfunction。 请参阅: http : //protovis-js.googlecode.com/svn/trunk/jsdoc/symbols/pv.Nest.html

我怎么能在Ruby中做到这一点?

如果将所有不同的哈希值放入一个数组中,则可以使用group_by将具有相同country_id哈希值组合在一起。 然后,您可以使用inject with merge它们merge在一起:

 country_info_and_stats = country_info + country_stats country_info_and_stats.group_by {|x| x[:country_id]}.map do |k,v| v.inject(:merge) end #=> [{:country_id=>"US", :country_desc=>"United States", :pageviews=>150}, # {:country_id=>"AU", :country_desc=>"Australia", :pageviews=>200}]