在Ruby中从数组内部选择一个哈希。

27

我有以下数组:

response = [{"label"=>"cat", "name"=>"kitty", "id"=>189955}, {"label" => "dog", "name"=>"rex", "id" => 550081}]
如何选择包含标签“cat”的哈希?我知道response.first将给我相同的结果,但我想按标签搜索。
谢谢!
Deb
2个回答

49
response.find {|x| x['label'] == 'cat' } #=> {"label"=>"cat", "name"=>"kitty", "id"=>189955}

15

请尝试:

response.select { |x| x["label"] == "cat" }

在这种特定情况下,选择也可以工作,但它返回一个数组,所以我会选择“查找”。谢谢! :) - deb
7
是的,Array#find返回第一个匹配项或nil,而Array#selectArray#find_all返回所有匹配元素的数组。 - Zargony
3
值得注意的是,Array#find 的一个同义词是 Array#detect - PreciousBodilyFluids

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接