加入哈希的阵列中的Ruby [英] Joining arrays of hashes in Ruby

查看:84
本文介绍了加入哈希的阵列中的Ruby的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想加入使用公共密钥的红宝石哈希的多个阵列。例如:

I am trying to join multiple arrays of hashes in ruby using a common key. For example:

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 。谷歌code.com / SVN /主干/ jsdoc /符号/ pv.Nest.html

This is something like the pv.nest function of protovis in Javascript. See: http://protovis-js.googlecode.com/svn/trunk/jsdoc/symbols/pv.Nest.html

我怎么能做到这一点的红宝石?

how can I do this in Ruby?

推荐答案

如果你把所有的不同的散列成一个阵列,可以使用 GROUP_BY 同组的那些同样 COUNTRY_ID 。然后,您可以使用合并合并那些一起

If you put all the different hashes into one array, you can use group_by to group together those with the same country_id. You can then use inject with merge to merge those together:

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}]

这篇关于加入哈希的阵列中的Ruby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆