"2012-08-15", "name"=>"John", "calls"=>"5"}, {"day"=>"2012-08-15-6ren">
gpt4 book ai didi

ruby - 给定散列中的多个其他值,如何在散列数组中查找并返回散列值

转载 作者:数据小太阳 更新时间:2023-10-29 06:56:37 26 4
gpt4 key购买 nike

我有这个哈希数组:

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

最佳答案

您走在正确的轨道上!

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

关于ruby - 给定散列中的多个其他值,如何在散列数组中查找并返回散列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12080115/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com