如何在哈希中给定多个其他值,在哈希数组中查找并返回哈希值

时间:2012-08-22 19:29:18

标签: ruby arrays hash

我有这个哈希数组:

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"},
]

如何搜索结果以查找Bill在15日拨打了多少电话?

在阅读“Ruby easy search for key-value pair in an array of hashes”的答案后,我认为可能涉及扩展以下发现声明:

results.find { |h| h['day'] == '2012-08-15' }['calls']

5 个答案:

答案 0 :(得分:15)

你走在正确的轨道上!

results.find {|i| i["day"] == "2012-08-15" and i["name"] == "Bill"}["calls"]
# => "8"

答案 1 :(得分:1)

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

答案 2 :(得分:0)

一个非常笨拙的实现;)

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 

答案 3 :(得分:0)

实际上,“减少”或“注入”专门用于此精确操作(将可枚举的内容减少为单个值:

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

这里的好写: “Understanding map and reduce

答案 4 :(得分:0)

或者另一种可能的方式,但更糟糕的是,使用注入:

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

请注意,您必须在每次迭代中设置number_of_calls,否则它将无效,例如这不起作用:

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