Ruby – The “for” loop

Here’s an example of the for loop:

for i in [1,2,3]
  puts i
end

This outputs:

PS C:\Temp\irb> ruby .\for.rb
1
2
3
PS C:\Temp\irb>

You can also iterate through a range, e.g.:

for i in (1..15)    # Notice that we used round bracket here. 
  puts i
end

The “..” indicates that we are interested in a range.

This outputs:

PS C:\Temp\irb> ruby .\for.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
PS C:\Temp\irb>

Note, the for loop actually makes use of the “each” method behind the scenes. More about this in the next lesson.