How do I replace a for-loop in Ruby?

for-loop, ruby

Solution

If you want to iterate over a collection and keep track of the index, use `each_with_index`:

fields = ["name", "age", "height"]

fields.each_with_index do |field,i|
  puts "#{i}. #{field}" # 0. name, 1. age, 2. height
end

Your `for i in 0...size` example becomes:

array1.each_with_index do |item, i|
  puts item
  puts array2[size-1 - i]
  puts i % 2
end

Problem

In Ruby it is bad style to use for-loops. This is commonly understood. A style guide recommended to me: (https://github.com/bbatsov/ruby-style-guide#source-code-layout) says: "Never use for, unless you know exactly why. Most of the time iterators should be used instead. for is implemented in terms of each (so you're adding a level of indirection), but with a twist - for doesn't introduce a new scope (unlike each) and variables defined in its block will be visible outside it." The example given is: ``` arr = [1, 2, 3] #bad for elem in arr do puts elem end # good arr.each { |elem| puts elem } ``` I have researched and I can't find an explanation as to how to simulate a for loop that provides an iterating value I can pass to places or perform arithmetic on. For example, with what would I replace: ``` for i in 0...size do puts array1[i] puts array2[size-1 - i] puts i % 2 end ``` It's easy if it's one array, but I often need the current position for other purposes. There's either a simple solution I'm missing, or situations where for is required. Additionally, I hear people talk about for as if it is never needed. What then is their solution to this? Can it be improved? And what is the solution, if there is one? Thanks.

Original source