When you loop with for you execute the code once for each element in the expression. When looping with for a range is defined, in this case the code will execute according to the values between 0 and 5.
for i in 0..5 puts "Value of local variable is #{i}" end
(0..5).each do |i| puts "Value of local variable is #{i}" end
Loops in Ruby are used to execute the same code a certain number of times. The While loop executes code while the conditional is true.
while conditional [do] code end
Looping with Until is similar to looping with While except for the code is executed until the conditional is true. Therefore it executes the code as long as the conditional remains false.
until conditional [do] code end
The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
for ([initialization]; [condition]; [final-expression]) statement;
The following for statement starts by declaring the variable i and initializing it to 0. It checks that i is less than nine, performs the two succeeding statements, and increments i by 1 after each pass through the loop.
for (var i = 0; i < 9; i++) { console.log(i); // more statements }
The while statement creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
while (condition) { statement }
The following while loop iterates as long as n is less than three.
var n = 0; var x = 0; while (n < 3) { n++; x += n; }
The for..in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
for (variable in object) {... }
The following function takes as its argument an object. It then iterates over all the object's enumerable properties and returns a string of the property names and their values.
var obj = {a:1, b:2, c:3}; for (var prop in obj) { console.log("o." + prop + " = " + obj[prop]); } // Output: // "o.a = 1" // "o.b = 2" // "o.c = 3"