"https://company.campfirenow.com", "name"=>"Company", "id"=>123456789, "produ-6ren">
gpt4 book ai didi

Ruby 轻松搜索哈希数组中的键值对

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

假设我有这个哈希数组:

[
{"href"=>"https://company.campfirenow.com", "name"=>"Company", "id"=>123456789, "product"=>"campfire"},
{"href"=>"https://basecamp.com/123456789/api/v1", "name"=>"Company", "id"=>123456789, "product"=>"bcx"},
{"href"=>"https://company.highrisehq.com", "name"=>"Company", "id"=>123456789, "product"=>"highrise"}
]

如何解析 "product"=>"bcx" 的散列值的“href

在 Ruby 中有什么简单的方法可以做到这一点吗?

最佳答案

ary = [
{"href"=>"https://company.campfirenow.com", "name"=>"Company", "id"=>123456789, "product"=>"campfire"},
{"href"=>"https://basecamp.com/123456789/api/v1", "name"=>"Company", "id"=>123456789, "product"=>"bcx"},
{"href"=>"https://company.highrisehq.com", "name"=>"Company", "id"=>123456789, "product"=>"highrise"}
]

p ary.find { |h| h['product'] == 'bcx' }['href']
# => "https://basecamp.com/123456789/api/v1"

请注意,这仅在元素存在时有效。否则,您将在 nil 上调用订阅操作符 [],这将引发异常,因此您可能需要先检查一下:

if h = ary.find { |h| h['product'] == 'bcx' }
p h['href']
else
puts 'Not found!'
end

如果您需要多次执行该操作,您应该自己构建一个数据结构以加快查找速度:

href_by_product = Hash[ary.map { |h| h.values_at('product', 'href') }]
p href_by_product['campfire'] # => "https://company.campfirenow.com"
p href_by_product['bcx'] # => "https://basecamp.com/123456789/api/v1"

关于Ruby 轻松搜索哈希数组中的键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10584326/

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