2012-08-22 41 views
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"}, 
] 

如何搜索的結果中找到多少個電話比爾十五號製造?

看完的答案爲「Ruby easy search for key-value pair in an array of hashes」,我認爲這可能涉及在下面查找聲明擴張:

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

回答

15

你在正確的軌道上!

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

我曾嘗試在那裏逗號,但你的_and_完美的作品!非常感謝。 – s2t2

+4

@ s2t2你也可以使用'&&'instad if'和' – PriteshJ

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版本,如果你確信你只有一個記錄每個組合 – PriteshJ

+0

我每個組合只有一個記錄。謝謝。 – s2t2

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

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