循环遍历ActiveRecord rails

时间:2011-10-29 23:13:43

标签: ruby-on-rails activerecord

我知道我能做到

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

但我想知道我是否可以使用for

循环@somethings

我试过

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

但据我所知,它没有给我我想要的物体或任何物体。

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

2 个答案:

答案 0 :(得分:3)

如果你正在使用的集合是可枚举的,你可以使用each_with_index方法,如下所示:

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

这几乎可以肯定你想要的。

答案 1 :(得分: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