Bird
Raised Fist0
Rubyprogramming~10 mins

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

Choose your learning style10 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?
No→End 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.

Practice

(1/5)
1. What does the each method do in Ruby when used on an array?
easy
A. It returns a new array with modified items.
B. It runs a block of code once for every item in the array.
C. It changes the array by removing items.
D. It sorts the array in ascending order.

Solution

  1. Step 1: Understand the purpose of each

    The each method is used to run a block of code for every item in a collection like an array.
  2. Step 2: Check what each does to the array

    It does not change or sort the array; it simply processes each item one by one.
  3. Final Answer:

    It runs a block of code once for every item in the array. -> Option B
  4. Quick Check:

    each runs code on each item [OK]
Hint: Remember: each processes items, does not change array [OK]
Common Mistakes:
  • Thinking each modifies the array
  • Confusing each with methods like map
  • Assuming each returns a new array
2. Which of the following is the correct syntax to use each on an array numbers to print each number?
easy
A. each numbers { |num| puts num }
B. numbers.each do num puts num end
C. numbers.each { |num| puts num }
D. numbers.each |num| puts num

Solution

  1. Step 1: Identify correct block syntax with each

    The correct syntax uses each followed by a block with { |variable| ... } or do |variable| ... end.
  2. Step 2: Check each option

    numbers.each { |num| puts num } uses numbers.each { |num| puts num } which is correct. Others have syntax errors or wrong order.
  3. Final Answer:

    numbers.each { |num| puts num } -> Option C
  4. Quick Check:

    Correct block syntax = numbers.each { |num| puts num } [OK]
Hint: Use each { |item| ... } or each do |item| ... end [OK]
Common Mistakes:
  • Writing each numbers instead of numbers.each
  • Missing block delimiters like braces or do-end
  • Not using pipes | | around block variable
3. What is the output of this Ruby code?
fruits = ['apple', 'banana', 'cherry']
fruits.each { |fruit| puts fruit.upcase }
medium
A. APPLE BANANA CHERRY
B. apple banana cherry
C. ['APPLE', 'BANANA', 'CHERRY']
D. Error: undefined method upcase for fruit

Solution

  1. Step 1: Understand what each does with puts fruit.upcase

    The each method runs the block for each fruit, printing the uppercase version.
  2. Step 2: Check output line by line

    It prints 'APPLE', then 'BANANA', then 'CHERRY' each on a new line.
  3. Final Answer:

    APPLE BANANA CHERRY -> Option A
  4. Quick Check:

    each prints uppercase fruits [OK]
Hint: Remember puts prints each item on a new line [OK]
Common Mistakes:
  • Thinking each returns a new array
  • Expecting lowercase output
  • Confusing puts with returning a list
4. What is wrong with this Ruby code snippet?
items = [1, 2, 3]
items.each do item
  puts item * 2
end
medium
A. Array items is empty
B. Using do instead of braces is invalid
C. Cannot multiply numbers inside each
D. Missing pipes around block variable: should be |item|

Solution

  1. Step 1: Check block variable syntax in each do block

    When using do with each, the block variable must be inside pipes: do |item|.
  2. Step 2: Identify the error

    The code misses pipes around item, causing a syntax error.
  3. Final Answer:

    Missing pipes around block variable: should be |item| -> Option D
  4. Quick Check:

    Block variables need pipes | | [OK]
Hint: Always put block variables inside | | with each do [OK]
Common Mistakes:
  • Omitting pipes around block variables
  • Thinking do is invalid with each
  • Assuming multiplication inside each is wrong
5. Given a hash scores = { alice: 10, bob: 15, carol: 12 }, how can you use each to print each name and score in the format Name: Score?
hard
A. scores.each { |name, score| puts "#{name.capitalize}: #{score}" }
B. scores.each { |score, name| puts "#{name}: #{score}" }
C. scores.each { |name| puts "#{name}: #{score}" }
D. scores.each { |name, score| puts "#{score.capitalize}: #{name}" }

Solution

  1. Step 1: Understand each on a hash

    When using each on a hash, the block receives two variables: key and value.
  2. Step 2: Match variables and format output

    The key is the name (symbol), value is the score. Use name.capitalize to print the name nicely.
  3. Final Answer:

    scores.each { |name, score| puts "#{name.capitalize}: #{score}" } -> Option A
  4. Quick Check:

    Hash each uses key, value pairs [OK]
Hint: Hash each block gets two vars: key and value [OK]
Common Mistakes:
  • Swapping key and value variables
  • Using only one block variable for hash
  • Trying to capitalize a number
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard