如何在包含多个其他值的哈希中查找并返回哈希值数组中的哈希值

7
我有一个哈希数组:
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个回答

15

你已经走上了正确的轨道!

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

1
我之前尝试过在那里加逗号,但是你的“和”完美地起作用了!非常感谢。 - s2t2
4
@s2t2,你也可以使用 && 代替 and - Pritesh Jain

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

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 

1
如果您确定每个组合只有一条记录,可以使用@ARun32版本。 - Pritesh Jain
我每个组合只有一条记录。谢谢。 - s2t2

0
实际上,“reduce”或“inject”是专门用于这个操作的(将可枚举对象的内容减少为单个值:)。
results.reduce(0) do |count, value|
  count + ( value["name"]=="Bill" && value["day"] == "2012-08-15" ? value["calls"].to_i : 0)
end

这里有一篇不错的文章: "理解map和reduce"


0

或者另一种可能的方式,但稍微差一些,是使用inject:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接