Menu
Coddy logo textTech

For Loop with Ranges

Part of the Fundamentals section of Coddy's Ruby journey — lesson 39 of 88.

Loops let you repeat code multiple times without writing it over and over. In Ruby, the for loop combined with a range is a straightforward way to iterate through a sequence of numbers.

A range in Ruby represents a sequence of values. You create one using two dots between a start and end value. Here's how to loop through numbers 1 to 5:

for i in 1..5
  puts i
end

This outputs each number from 1 to 5, each on its own line. The variable i takes on each value in the range, one at a time, and the code inside the loop runs for each value.

Ruby has two types of ranges. The two-dot range 1..5 includes both endpoints (1, 2, 3, 4, 5). The three-dot range 1...5 excludes the last number (1, 2, 3, 4):

for num in 1...4
  puts num
end
# Outputs: 1, 2, 3

You can use any variable name you like and perform operations inside the loop. For example, printing the square of each number:

for n in 1..3
  puts n * n
end
# Outputs: 1, 4, 9
challenge icon

Challenge

Easy

Read a number n from input. Use a for loop with a range to print all numbers from 1 to n, each on its own line.

The input will be a single integer representing the upper limit of the range.

For example, if the input is 4, the output should be:

1
2
3
4

Cheat sheet

The for loop with a range allows you to iterate through a sequence of numbers:

for i in 1..5
  puts i
end

Ruby has two types of ranges:

  • 1..5 - includes both endpoints (1, 2, 3, 4, 5)
  • 1...5 - excludes the last number (1, 2, 3, 4)
for num in 1...4
  puts num
end
# Outputs: 1, 2, 3

You can use any variable name and perform operations inside the loop:

for n in 1..3
  puts n * n
end
# Outputs: 1, 4, 9

Try it yourself

# Read the number from input
n = gets.to_i

# TODO: Write your code below
# Use a for loop with a range to print all numbers from 1 to n
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals