2016-02-26 92 views
-4

有没有办法在类对象数组中找到值。然后一旦发现它被包含,你能找到它所在的数组内的什么地方?例如。查找类对象数组中的值

class SomeClass 
def initialize(value,otherData) 
     @value = value 
     @otherData = otherData 
end 
end 

x = 0 
otherData = "foo" 
list = Array.new 
while (x < 3) 
    list.push SomeClass.new(x,otherData) 
    x += 1 
end 

我想查找list [x] .value where value = 2并找出数组中位于的位置。

+0

你的代码是无效的。什么是“价值”方法?你的骆驼案件本地变量给人的印象非常糟糕。 – sawa

+0

我想你只需遍历对象数组,看看对象内的值,然后从那里开始 –

+0

http://ruby-doc.org/core-2.2.0/Array.html#method-i -find_index – matt

回答

1

如果SomeClass的有value方法,一个明显的方法是:

ix = list.find_index { |sc| sc.value == 2 }