简体   繁体   中英

Joining arrays of hashes in 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}
]

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM