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!"
endThis 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, 3The 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 3The times loop is perfect when you know exactly how many repetitions you need and want clean, readable code.
Challenge
EasyRead 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 = 6If 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 = 10Cheat sheet
The times loop repeats code a specific number of times:
3.times do
puts "Hello!"
endTo access the current iteration number (starting from 0), use a variable between pipes:
4.times do |i|
puts i
end
# Outputs: 0, 1, 2, 3You can use the index variable in calculations:
3.times do |num|
puts "Iteration #{num + 1}"
end
# Outputs: Iteration 1, Iteration 2, Iteration 3Try 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]This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False