Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

ruby

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']
like image 890
s2t2 Avatar asked Aug 22 '12 19:08

s2t2


People also ask

How do you access an array of hashes?

Accessing an array of hashes You can access the elements of an array of hashes by using array-based indexing to access a particular hash and keys to access values present in that hash.

Can a hash have multiple values?

You can only store scalar values in a hash. References, however, are scalars. This solves the problem of storing multiple values for one key by making $hash{$key} a reference to an array containing values for $key .

How do you check if a value exists in a hash?

Overview. A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false .

Can we get the original value from hash?

The cryptographic hashing of a value cannot be inverted to find the original value. Given a value, it is infeasible to find another value with the same cryptographic hash.


2 Answers

You're on the right track!

results.find {|i| i["day"] == "2012-08-15" and i["name"] == "Bill"}["calls"]
# => "8"
like image 70
ARun32 Avatar answered Sep 21 '22 18:09

ARun32


results.select { |h| h['day'] == '2012-08-15' && h['name'] == 'Bill' }
  .reduce(0) { |res,h| res += h['calls'].to_i } #=> 8
like image 26
megas Avatar answered Sep 18 '22 18:09

megas