Ruby - Looping Through Numbers with Blocks and Iterators


Here's a basic way to implement a loop:


5.times do puts "Test" end


First, you take the number 5.

Next, you call the times method, common to all numbers in Ruby.

Then you pass in the code between do and end.

The times method then uses the code five times in succession, producing the preceding five lines of output.

Another way to write this is with curly brackets instead of do and end.


5.times { puts "Test" }


Other iterators are available for numbers, such as the following:

1.upto(5) { ...code to loop here... } 
10.downto(5) { ...code to loop here... } 
0.step(50, 5) { ...code to loop here... } 

The first example counts from 1 up to 5.

The second example counts from 10 down to 5.

The last example counts up from 0 to 50 in steps of 5, because you're using the step method on the number 0.

Related Example