[英]How to find and return a hash value within an array of hashes, given multiple other values in the 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在一系列哈希中轻松搜索键值对”的答案后,我认为它可能涉及扩展以下查找语句:
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
实际上,“reduce”或“inject”专门针对此精确操作(将可枚举的内容减少为单个值:
results.reduce(0) do |count, value|
count + ( value["name"]=="Bill" && value["day"] == "2012-08-15" ? value["calls"].to_i : 0)
end
好的写在这里:“ 了解地图并减少 ”
或者另一种可能的方式,但更糟糕的是,使用注入:
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'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.