什么是优雅的'ruby'方式(如果重要的话,在rails中)在使用list.each时每隔N次迭代改变一个循环的函数?

Ecn*_*lyr 0 ruby loops ruby-on-rails

什么是优雅的'ruby'方法来改变每第N次迭代的循环函数?我宁愿不使用,(1..50).each do |i|因为我想迭代列表中的每个对象objects.

  objects.each do |object|
   #Do this with object information
   #Do not do this if this is the third time through the loop
  end
Run Code Online (Sandbox Code Playgroud)

Ser*_*sev 5

objects.each_with_index do |object, idx|
   if idx == 2 # third time

   # or
   # if idx % 3 == 2 # every third time

     # do special thing
   else
     # do normal thing
   end
end
Run Code Online (Sandbox Code Playgroud)