0
0
Rubyprogramming~10 mins

Each as the primary iterator in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Each as the primary iterator
Start with collection
Call each method
Take first element
Execute block with element
Move to next element
More elements?
NoEnd iteration
Back to Execute block
The each method takes one element at a time from a collection and runs the given block on 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
StepCurrent Element (num)Block ExecutionOutputNext Action
11puts 1 * 22Move to next element
22puts 2 * 24Move to next element
33puts 3 * 26No more elements, end iteration
💡 All elements processed, each iteration ends
Variable Tracker
VariableStartAfter 1After 2After 3Final
numnil123nil
Key Moments - 3 Insights
Why does the variable 'num' change each time in the block?
Because 'each' takes one element at a time from the collection and assigns it to 'num' before running the block, as shown in steps 1 to 3 in the execution_table.
What happens after the last element is processed?
The iteration stops because there are no more elements to assign to 'num', as explained in the exit_note and step 3 of the execution_table.
Does 'each' change the original collection?
No, 'each' only reads elements one by one and runs the block; it does not modify the original collection.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'num' at step 2?
A1
B3
C2
Dnil
💡 Hint
Check the 'Current Element (num)' column at step 2 in the execution_table.
At which step does the iteration end according to the execution_table?
AStep 1
BAfter Step 3
CStep 3
DStep 2
💡 Hint
Look at the 'Next Action' column and the exit_note for when iteration stops.
If the array had one more element, how would the execution_table change?
AThere would be an extra step with that element as 'num'.
BThe iteration would stop earlier.
CThe output would be empty.
DThe variable 'num' would not change.
💡 Hint
Refer to how each element is processed step-by-step in the execution_table.
Concept Snapshot
each method syntax:
collection.each do |element|
  # code using element
end

Behavior:
- Takes one element at a time
- Runs block with that element
- Continues until all elements done
- Does not modify original collection
Full Transcript
The 'each' method in Ruby goes through every item in a collection one by one. For each item, it assigns it to a variable (like 'num') and runs the code inside the block. This continues until all items are processed. The original collection stays the same. In the example, numbers 1, 2, and 3 are doubled and printed. The variable 'num' changes each step to the current element. When no elements remain, the iteration ends.