How to find and return a hash value within an array of hashes, given multiple other values in the hash
13,304
Solution 1
You're on the right track!
results.find {|i| i["day"] == "2012-08-15" and i["name"] == "Bill"}["calls"]
# => "8"
Solution 2
results.select { |h| h['day'] == '2012-08-15' && h['name'] == 'Bill' }
.reduce(0) { |res,h| res += h['calls'].to_i } #=> 8
Author by
s2t2
Updated on June 11, 2022Comments
-
s2t2 almost 2 years
I have this array of hashes:
results = [ {"day"=>"2012-08-15", "name"=>"John", "calls"=>"5"}, {"day"=>"2012-08-15", "name"=>"Bill", "calls"=>"8"}, {"day"=>"2012-08-16", "name"=>"Bill", "calls"=>"11"}, ]
How can I search the results to find how many calls Bill made on the 15th?
After reading the answers to "Ruby easy search for key-value pair in an array of hashes", I think it might involve expanding upon the following find statement:
results.find { |h| h['day'] == '2012-08-15' }['calls']