0
0
Rubyprogramming~10 mins

Times method for counted repetition in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Times method for counted repetition
Start with number n
Call n.times do |i|
Execute block with i from 0 to n-1
Repeat until i == n-1
Exit loop
The times method runs a block of code n times, passing the current count from 0 up to n-1.
Execution Sample
Ruby
3.times do |i|
  puts i
end
Prints numbers 0, 1, and 2 each on a new line using times method.
Execution Table
Iterationi (block variable)ActionOutput
10Execute block with i=00
21Execute block with i=11
32Execute block with i=22
Exit-i reached 3, loop ends-
💡 i reaches 3, which equals n, so times loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
i-012-
Key Moments - 2 Insights
Why does the block variable i start at 0 instead of 1?
The times method counts from 0 up to n-1, so i starts at 0 as shown in the execution_table rows 1-3.
Does the times method include the number n in the block variable?
No, the block variable i goes up to n-1. The loop exits when i reaches n, as shown in the exit row.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of i during the second iteration?
A1
B0
C2
D3
💡 Hint
Check the 'i (block variable)' column in the second row of execution_table.
At which iteration does the times method stop running the block?
AAfter iteration 2
BAfter iteration 3
CAfter iteration 4
DNever stops
💡 Hint
Look at the exit row in execution_table where i reaches 3 and loop ends.
If we change 3.times to 5.times, how many rows will the execution_table have before exit?
A3
B4
C5
D6
💡 Hint
The times method runs the block n times, so 5.times runs 5 iterations.
Concept Snapshot
times method syntax:
number.times do |i|
  # code using i
end

Runs block n times with i from 0 to n-1.
Useful for counted repetition without manual loops.
Block variable i starts at 0, ends at n-1.
Full Transcript
The times method in Ruby runs a block of code a set number of times. It starts counting from zero and goes up to one less than the number. For example, 3.times do |i| runs the block three times with i values 0, 1, and 2. Each iteration executes the block with the current i. When i reaches the number, the loop stops. This method is a simple way to repeat code a fixed number of times without writing a manual loop.