2011-10-29 51 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在你想要的。