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

我如何搜索结果以找到比尔在 15 日打了多少电话?

在阅读“ Ruby easy search for key-value pair in an hashes array ”的答案后,我认为它可能涉及扩展以下 find 语句:

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

5 回答 5

15

你在正确的轨道上!

results.find {|i| i["day"] == "2012-08-15" and i["name"] == "Bill"}["calls"]
# => "8"
于 2012-08-22T19:44:20.337 回答
1
results.select { |h| h['day'] == '2012-08-15' && h['name'] == 'Bill' }
  .reduce(0) { |res,h| res += h['calls'].to_i } #=> 8
于 2012-08-22T19:48:23.730 回答
0

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

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

不错的文章:“理解 map 和 reduce

于 2012-08-22T20:05:10.210 回答
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'}
于 2012-08-22T20:11:57.067 回答
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 
于 2012-08-22T19:44:00.443 回答