我正在尝试使用公共密钥加入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.nest功能。请参阅:http://protovis-js.googlecode.com/svn/trunk/jsdoc/symbols/pv.Nest.html
我怎么能在Ruby中做到这一点?
答案 0 :(得分:9)
如果将所有不同的哈希值放入一个数组中,则可以使用group_by
将具有相同country_id
的哈希值组合在一起。然后,您可以inject
与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}]
:
{{1}}