ruby can repeat a code block with a for loop. All for loops have a condition, this can be the amount of times or a list.

You need loops to repeat code: instead of repeating the instructions over and over, simply tell ruby to do it n times.

Related course:
Learn Rails 5.2: Accelerated Web Development with Ruby on Rails

For loops in ruby


The program below is an example of a for loop in ruby. The for loop is used to repeat the code block.

Ruby will jump out of the code block once the condition is true, but it won’t end the program.

The code block can contain anything, from statements to function calls.


for i in 0..4
puts "Iteration #{i}"

The code block can be as many lines as you want, in this example its just one line of code that gets repeated.

ruby runs the code block only n times. The number of repetitions is called iterations and every round is called an iteration.

To start save it as forloops.rb, then type this command:

ruby forloops.rb


  1. Can for loops exist inside for loops?
  2. Make a program that counts from 1 to 10.