简体   繁体   中英

How to find and return a hash value within an array of hashes, given multiple other values in the hash

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

You're on the right track!

results.find {|i| i["day"] == "2012-08-15" and i["name"] == "Bill"}["calls"]
# => "8"
results.select { |h| h['day'] == '2012-08-15' && h['name'] == 'Bill' }
  .reduce(0) { |res,h| res += h['calls'].to_i } #=> 8

A Really clumsy implementation ;)

def get_calls(hash,name,date) 
 hash.map{|result| result['calls'].to_i if result['day'] == date && result["name"] == name}.compact.reduce(:+)
end

date = "2012-08-15"
name = "Bill"

puts get_calls(results, name, date)
=> 8 

Actually, "reduce" or "inject" is specifically for this exact operation (To reduce the contents of an enumerable down into a single value:

results.reduce(0) do |count, value|
  count + ( value["name"]=="Bill" && value["day"] == "2012-08-15" ? value["calls"].to_i : 0)
end

Nice writeup here: " Understanding map and reduce "

Or another possible way, but a little worse, using inject:

results.inject(0) { |number_of_calls, arr_element| arr_element['day'] == '2012-08-15' ? number_of_calls += 1 : number_of_calls += 0  }

Note that you have to set number_of_calls in each iteration, otherwise it will not work, for example this does NOT work:

p results.inject(0) { |number_of_calls, arr_element| number_of_calls += 1 if arr_element['day'] == '2012-08-15'}

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