ruby数组包含一个id

时间:2010-12-11 19:30:10

标签: ruby

我目前想迭代一个对象数组(2个属性:id& name)并检查数组是否包含特定的Id

我该怎么做?

2 个答案:

答案 0 :(得分:6)

Enumerable#detect没问题,但我认为Enumerable#any?(返回一个布尔值)严格按照你的要求:

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

答案 1 :(得分:2)

尝试detect

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