在Ruby中加入哈希数组
发布时间:2020-12-17 03:44:24 所属栏目:百科 来源:网络整理
导读:我正在尝试使用公共密钥加入 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",pagev
我正在尝试使用公共密钥加入
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_desc: "Australia",pageviews:200} ] 这类似于Javascript中protovis的pv.nest功能.见:http://protovis-js.googlecode.com/svn/trunk/jsdoc/symbols/pv.Nest.html 我怎么能在Ruby中做到这一点? 解决方法
如果将所有不同的哈希值放入一个数组中,则可以使用group_by将具有相同country_id的哈希值组合在一起.然后,您可以使用inject with 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}] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |