Menu
Coddy logo textTech

Times Loop

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

Ruby offers a more elegant way to repeat code a specific number of times. The times loop is a Ruby-style approach that reads almost like English.

Instead of setting up a range, you simply call times on a number:

3.times do
  puts "Hello!"
end

This prints "Hello!" three times. The code inside the do...end block runs exactly 3 times. It's cleaner than writing for i in 1..3 when you don't need the counter variable.

But what if you do need to know which iteration you're on? The times loop can provide an index that starts at 0:

4.times do |i|
  puts i
end
# Outputs: 0, 1, 2, 3

The variable i between the pipes |i| receives the current iteration number. Notice it counts from 0, not 1. This is useful when you need both the repetition and a counter:

3.times do |num|
  puts "Iteration #{num + 1}"
end
# Outputs: Iteration 1, Iteration 2, Iteration 3

The times loop is perfect when you know exactly how many repetitions you need and want clean, readable code.

challenge icon

Challenge

Easy

Read a number n from input. Use the times loop with its index to print a multiplication table for the number 2, showing products from 2 x 0 up to 2 x (n-1).

Each line should follow the format: 2 x [index] = [result]

The input will be a single integer representing how many times the loop should run.

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

2 x 0 = 0
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6

If the input is 6, the output should be:

2 x 0 = 0
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10

Cheat sheet

The times loop repeats code a specific number of times:

3.times do
  puts "Hello!"
end

To access the current iteration number (starting from 0), use a variable between pipes:

4.times do |i|
  puts i
end
# Outputs: 0, 1, 2, 3

You can use the index variable in calculations:

3.times do |num|
  puts "Iteration #{num + 1}"
end
# Outputs: Iteration 1, Iteration 2, Iteration 3

Try it yourself

# Read the number of iterations
n = gets.to_i

# TODO: Write your code below
# Use the times loop with its index to print the multiplication table for 2
# Format: 2 x [index] = [result]
quiz iconTest yourself

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

All lessons in Fundamentals