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.

Download Free Ruby Ebook

For loops in ruby

Example

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.

1
2
3
4
5
#!/usr/bin/ruby

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

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:

1
ruby forloops.rb

Exercises

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