2011-10-29 65 views
1

我知道我可以做遍历ActiveRecord的轨道

@somethings.each do |something| 
/*some work with something*/ 
end 

,但我想知道如果我能遍历一个@somethings为

我试图

for i in 0..10 
    @somethings[i].myattribute 
end 

但不会给我我想要的物体或任何物体,据我所知。

我需要使用for循环,我不能做我想要的“每个”。那么是否有可能以某种方式使用for循环?

+0

好吧,如果您必须知道:我正在使用Rhomobile开发我的应用程序,但我无法按照需要对记录进行排序,所以或者我可以使用for循环以我想要的方式遍历记录。 – marimaf

+0

适用于我,假设您的第二个示例中存在拼写错误。 –

+0

谢谢,这是我的错字,我修好了 – marimaf

回答

1
for something in @somethings 
    something.myattribute 
end 

或怪异的

@somethings_array = @somethings.to_a 
for i in 0..10 
    @somethings_array[i].myattribute 
end 

确定

@somethings_array = @somethings.to_a 
10.downto(1) do |i| 
    @somethings_array[i].myattribute 
end 
+0

谢谢,但那不是我正在寻找的。我需要索引 – marimaf

+0

好的,我已经更新了答案 – fl00r

+0

谢谢!它的工作 – marimaf

3

如果您正在使用的集合是枚举,你可以使用each_with_index方法,像这样:

@somethings.each_with_index do |something, i| 
    something[i].an_attribute 
end 

这应该几乎可以肯定地做wh在你想要的。