我有一个由哈希组成的数组:
people = [{'name':'Bob','id':12}, {'name':'Sam','id':25}, ...etc]
是否有任何简单的方法来检查数组 people 是否包含例如包含 id 16 的哈希?
如果这可以用另一种数据结构来完成,请提出建议。我并不固执地使用哈希。我只需要存储名称和 ID(以后可能会扩展到更多字段)。
如果这有助于您的解释,我来自 Java/C 背景。
Enumerable#find
, Enumerable#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