我正在尝试使用公共密钥加入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}
]
Run Code Online (Sandbox Code Playgroud)
这类似于Javascript中protovis的pv.nest功能.请参阅:http://protovis-js.googlecode.com/svn/trunk/jsdoc/symbols/pv.Nest.html
我怎么能在Ruby中做到这一点?
如果将所有不同的哈希值放在一个数组中,则可以将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}]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1734 次 |
| 最近记录: |