Ruby - For Loop
The for loop executes a set of statements in each iteration. Whenever, number of iteration is known, for loop is preferred over while loop. A for loop expression is separated from code by the reserved word do, a newline, or a semicolon.
Syntax
for variable [, variable ...] in expression [do] statements end
Example:
In the example below, the program continue to print variable called i from value 1 to 5. After that, it exits from the for loop.
for i in 1..5 do puts "Value of i = #{i}" end
The output of the above code will be:
Value of i = 1 Value of i = 2 Value of i = 3 Value of i = 4 Value of i = 5
Example: for loop over an array
A for loop can be used to access elements of an array. Consider the example below:
MyStr = ["Red", "Blue", "Green"] for i in MyStr do puts i end
The output of the above code will be:
Red Blue Green
A for..in loop is almost equivalent to the each iterator used with sequence created using range operator.
#method 1 (expression).each do |variable| statements end #method 2 (expression).each { |variable| statements }
Example:
In the example below, the each iterator is used like a for loop.
#using each iterator like a for loop (5..10).each do |i| puts "Value of i = #{i}" end
The output of the above code will be:
Value of i = 5 Value of i = 6 Value of i = 7 Value of i = 8 Value of i = 9 Value of i = 10