0

我有一个由哈希组成的数组:

people = [{'name':'Bob','id':12}, {'name':'Sam','id':25}, ...etc]

是否有任何简单的方法来检查数组 people 是否包含例如包含 id 16 的哈希?

如果这可以用另一种数据结构来完成,请提出建议。我并不固执地使用哈希。我只需要存储名称和 ID(以后可能会扩展到更多字段)。

如果这有助于您的解释,我来自 Java/C 背景。

4

2 回答 2

1

像这样的东西?

people.select { |p| p[:id] == '16' }

select将遍历数组并返回结果

此外,您可以检测到仅获得第一个匹配项

于 2013-06-25T16:01:22.707 回答
1

Enumerable#findEnumerable#find_all并且Enumerable#any?是如下所示的好方法:

people = [{name:'Bob',id:'12'}, {name:'Sam',id:'25'}]
p people.find{ |i| i[:id] == '12' } # to find a single and first entry which satisfies the given condtion
# => {:name=>"Bob", :id=>"12"}


people = [{name:'Bob',id:'12'}, {name:'Sam',id:'25'},{name:'Max',id:'12'}]
p people.find_all{ |i| i[:id] == '12' } # to find a multiple entries which satisfies the given condtion
# => [{:name=>"Bob", :id=>"12"}, {:name=>"Max", :id=>"12"}]

people = [{name:'Bob',id:'12'}, {name:'Sam',id:'25'},{name:'Max',id:'12'}]
p people.any? { |i| i[:id] == '12' }
# => true
于 2013-06-25T16:01:54.517 回答