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}]
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加