0
0
Rubyprogramming~10 mins

Each for iteration in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Each for iteration
Start with collection
Pick next element
Run block with element
More elements?
NoEnd iteration
Back to Pick next element
The 'each' method takes each element from a collection one by one and runs the given block of code with it until all elements are processed.
Execution Sample
Ruby
numbers = [1, 2, 3]
numbers.each do |num|
  puts num * 2
end
This code goes through each number in the list and prints double its value.
Execution Table
Iterationnum valueActionOutput
11Run block with num=12
22Run block with num=24
33Run block with num=36
--No more elements, iteration ends-
💡 All elements processed, 'each' loop ends
Variable Tracker
VariableStartAfter 1After 2After 3Final
numnil123nil
Key Moments - 2 Insights
Why does 'num' change each iteration?
'num' takes the value of the current element from the collection each time the block runs, as shown in execution_table rows 1 to 3.
What happens after the last element is processed?
The loop stops because there are no more elements, as shown in the last row of execution_table where iteration ends.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'num' during iteration 2?
A1
B2
C3
Dnil
💡 Hint
Check the 'num value' column in the second row of execution_table.
At which iteration does the loop stop running the block?
AAfter iteration 1
BAfter iteration 2
CAfter iteration 3
DIt never stops
💡 Hint
Look at the exit note and the last row in execution_table.
If the array was empty, what would happen to the 'num' variable?
AIt would never be set and block never runs
BIt would be set to nil and block runs once
CIt would be set to 0
DIt would cause an error
💡 Hint
Refer to variable_tracker and understand that 'num' changes only when block runs.
Concept Snapshot
Ruby 'each' method:
- Goes through each element in a collection
- Runs the block with current element as variable
- Stops after last element
- Variable inside block changes each iteration
- No output unless block prints or returns
Full Transcript
The Ruby 'each' method takes a collection like an array and runs a block of code for each element. In the example, numbers 1, 2, and 3 are processed one by one. The variable 'num' holds the current element's value during each iteration. The block prints double the number. After all elements are done, the loop ends. If the array is empty, the block never runs and 'num' stays nil.