2010-12-11 136 views
1

我現在要遍歷對象的數組(2個屬性:id &名),並檢查該數組包含一個特定ID紅寶石陣列包括一個id

我將如何做到這一點?

+0

的可能重複[確定值存在於散列數組中](http://stackoverflow.com/questions/1514883/determine-if-a-value-exists-in-an-array-of-hashes) – 2011-12-12 22:03:44

回答

7

Enumerable#detect是好的,但我認爲Enumerable#any?(返回boolean),是嚴格的,你問什麼:

xs = [{:id => 1, :name => 'a'}, {:id => 2, :name => 'b'}] 
puts xs.any? {|x| x[:id] == 1} # true 
puts xs.any? {|x| x[:id] == 5} # false 
3

嘗試detect

a = [{:id => 1, :name => 'a'}, {:id => 2, :name => 'b'}] 
puts a.detect {|x| x[:id] == 1}