简体   繁体   中英

How to count items in arrays of values in an array of hashes

I have an array of hashes that contain an array of items as the hash value. Here's the structure:

arr = [
  {:title => "String1", :link => ["URL1", "URL2"]},
  {:title => "String2", :link => ["URL3", "URL4", "URL5"]}
]

I'd like to add a key-value pair that counts the items in each :link like this:

arr = [
  {:title => "String1", :link => ["URL1", "URL2"], :link_count => 2},
  {:title => "String2", :link => ["URL3", "URL4", "URL5"]}, :link_count => 3 
]

I can get to the counts of each :link using this:

arr.map{|x| x[:link].count}

but I can't persist the count as a new key. Any ideas?

You can simply do it by Array#each as below,

> arr.each { |h| h[:link_count] = h[:link].count }
# => [{:title=>"String1", :link=>["URL1", "URL2"], :link_count=>2}, {:title=>"String2", :link=>["URL3", "URL4", "URL5"], :link_count=>3}]  

You can use merge! method which alter the original array with the new changes.

arr.map { |x| x.merge!({ link_count: x[:link].count }) }

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