Ruby Language Reference

for statement

Syntax

for variable in expression
  p 'do something'
end

The for loop executes code for each element in the expression. This is equivalent to:

expression.each do |variable|
  p 'do something'
end

The only difference is that the for loop does not create a new scope for local variables.

Example

for x in (1..5)
  p x
end

This prints.

1
2
3
4
5

This is equivalent to:

(1..5).each do |x|
  p x
end


Sharing is Caring