我有这个散列数组:
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在哈希数组中轻松搜索键值对"的答案后,我认为这可能涉及扩展以下find语句:
results.find { |h| h['day'] == '2012-08-15' }['calls']
你走在了正确的轨道上!
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
一个非常笨拙的实现;)
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
或者另一种可能的方式,但更糟的是,使用注入:
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'}
实际上,"reduce"或"inject"专门用于此精确操作(要将可枚举对象的内容缩减为单个值:
results.reduce(0) do |count, value|
count + ( value["name"]=="Bill" && value["day"] == "2012-08-15" ? value["calls"].to_i : 0)
end
这里写得不错:"了解地图并减少"