Bird
Raised Fist0
Rubyprogramming~15 mins

Each as the primary iterator in Ruby - Deep Dive

Choose your learning style10 modes available
Overview - Each as the primary iterator
What is it?
In Ruby, 'each' is a method used to go through every item in a collection like an array or a hash. It runs a small piece of code you give it for each item, one by one. This lets you do something with each item easily without writing a loop yourself. It's a simple way to repeat actions for all elements in a group.
Why it matters
Without 'each', you would have to write manual loops to handle collections, which can be error-prone and less readable. 'Each' makes your code cleaner and easier to understand, saving time and reducing mistakes. It helps programmers focus on what to do with items, not how to loop through them.
Where it fits
Before learning 'each', you should understand basic Ruby syntax and what arrays and hashes are. After mastering 'each', you can explore other iterators like 'map', 'select', and 'reduce' to transform and filter collections more powerfully.
Mental Model
Core Idea
'Each' is like a helper that takes your instructions and applies them to every item in a collection, one at a time.
Think of it like...
Imagine you have a basket of apples and you want to paint each apple red. Instead of picking apples one by one yourself, you tell a friend to take each apple and paint it. Your friend is like 'each', doing the task for every apple automatically.
Collection: [item1, item2, item3, ...]

  each method:
  ┌───────────────┐
  │  item1 -> run │
  │  item2 -> run │
  │  item3 -> run │
  └───────────────┘

Result: Action applied to every item in order
Build-Up - 6 Steps
1
FoundationUnderstanding collections in Ruby
🤔
Concept: Learn what arrays and hashes are, the main collections you use with 'each'.
Arrays are ordered lists of items, like a shopping list. Hashes are collections of key-value pairs, like a dictionary where each word has a meaning. Both can hold many items and are common in Ruby.
Result
You can create and access items in arrays and hashes easily.
Knowing collections is essential because 'each' works by going through these groups one item at a time.
2
FoundationBasic syntax of 'each' method
🤔
Concept: Learn how to write 'each' to loop over an array or hash.
For an array: numbers = [1, 2, 3] numbers.each do |number| puts number end For a hash: fruits = {a: 'apple', b: 'banana'} fruits.each do |key, value| puts "#{key}: #{value}" end
Result
The program prints each number or key-value pair on its own line.
Understanding the block syntax with |variables| is key to using 'each' effectively.
3
IntermediateUsing 'each' with different collections
🤔Before reading on: Do you think 'each' works only with arrays or also with hashes and other collections? Commit to your answer.
Concept: 'Each' works with many collection types, not just arrays.
Besides arrays and hashes, 'each' can be used with ranges, sets, and custom collections that include the Enumerable module. For example: (1..3).each { |n| puts n } This prints numbers 1 to 3.
Result
You can loop over many kinds of collections with the same simple 'each' method.
Knowing 'each' works broadly helps you write flexible code that handles many data types.
4
IntermediateDifference between 'each' and manual loops
🤔Before reading on: Is 'each' just a shortcut for loops, or does it do something fundamentally different? Commit to your answer.
Concept: 'Each' abstracts looping, making code cleaner and less error-prone than manual loops.
Manual loop example: for i in 0...numbers.length puts numbers[i] end Using 'each': numbers.each { |num| puts num } The 'each' version is shorter, clearer, and less likely to cause off-by-one errors.
Result
Cleaner, safer code that focuses on what to do with items, not how to loop.
Understanding this abstraction helps you write idiomatic Ruby and avoid common loop mistakes.
5
AdvancedChaining 'each' and side effects
🤔Before reading on: Does 'each' return the transformed collection or something else? Commit to your answer.
Concept: 'Each' returns the original collection, not a transformed one, so it's mainly for side effects.
Example: result = [1, 2, 3].each { |n| puts n * 2 } puts result.inspect Output: 2 4 6 [1, 2, 3] This shows 'each' prints doubled numbers but returns the original array unchanged.
Result
'Each' is best for actions like printing or modifying external state, not for creating new collections.
Knowing 'each' returns the original collection prevents bugs when you expect a new array from it.
6
ExpertCustomizing 'each' in your own classes
🤔Before reading on: Can you make your own objects support 'each'? How? Commit to your answer.
Concept: You can define 'each' in your classes to make them iterable and compatible with Ruby's Enumerable methods.
Example: class Team include Enumerable def initialize(members) @members = members end def each @members.each { |member| yield member } end end team = Team.new(['Alice', 'Bob']) team.each { |m| puts m } This lets Team behave like a collection.
Result
Your custom objects can be looped over with 'each' and gain powerful Enumerable features.
Understanding this unlocks advanced Ruby design patterns and makes your classes more flexible.
Under the Hood
'Each' is a method defined on collection classes that takes a block of code. Internally, it loops over the collection's elements and calls the block with each element as an argument. The block is a chunk of code passed to the method, which Ruby executes for every item. After finishing, 'each' returns the original collection, allowing method chaining.
Why designed this way?
Ruby was designed to be readable and expressive. 'Each' abstracts away loop details so programmers can focus on actions per item. Returning the original collection allows chaining multiple methods smoothly. This design encourages writing clear, concise, and flexible code.
Collection (Array/Hash/Range)
   │
   ▼
+-----------------+
|  each method     |
|  ┌─────────────┐|
|  │ For each item│|
|  │  yield item  │|
|  └─────────────┘|
+-----------------+
   │
   ▼
Block runs on each item
   │
   ▼
Returns original collection
Myth Busters - 4 Common Misconceptions
Quick: Does 'each' create a new array with changed items? Commit to yes or no.
Common Belief:Many think 'each' transforms collections and returns a new one with changes.
Tap to reveal reality
Reality:'Each' only runs code on each item and returns the original collection unchanged.
Why it matters:Expecting a new collection from 'each' leads to bugs when changes are not saved or used.
Quick: Can 'each' be used without a block? Commit to yes or no.
Common Belief:Some believe 'each' can be called without giving it a block of code.
Tap to reveal reality
Reality:'Each' requires a block; calling it without one returns an Enumerator object instead of running code.
Why it matters:Not providing a block causes unexpected behavior or errors if you expect iteration to happen immediately.
Quick: Does 'each' guarantee order of iteration in all collections? Commit to yes or no.
Common Belief:People often assume 'each' always processes items in the order they were added.
Tap to reveal reality
Reality:For arrays and ranges, order is guaranteed; for hashes in modern Ruby, order is preserved; but for some collections like sets, order is not guaranteed.
Why it matters:Assuming order when it’s not guaranteed can cause subtle bugs in programs relying on sequence.
Quick: Does 'each' automatically stop if you return false inside the block? Commit to yes or no.
Common Belief:Some think returning false inside the 'each' block stops the iteration early.
Tap to reveal reality
Reality:'Each' always runs through all items; returning false or any value inside the block does not stop it.
Why it matters:Expecting early exit leads to unexpected full iteration and possible performance issues.
Expert Zone
1
When chaining methods, 'each' returning the original collection allows seamless integration with other Enumerable methods.
2
Defining 'each' in custom classes and including Enumerable unlocks a rich set of collection methods automatically.
3
Using 'each' with Enumerator objects enables lazy evaluation and complex iteration patterns.
When NOT to use
'Each' is not suitable when you want to transform collections and get new results; use 'map' instead. For filtering, use 'select'. For reducing to a single value, use 'reduce'. Avoid 'each' when you need early exit; use 'find' or 'detect' instead.
Production Patterns
In real-world Ruby code, 'each' is used for side effects like logging, printing, or updating external state. It's common to see 'each' combined with blocks that modify objects or write to files. Custom classes implement 'each' to integrate with Ruby's Enumerable, enabling powerful data handling.
Connections
Map-Reduce in Functional Programming
'Each' is related as the basic iteration step before mapping or reducing collections.
Understanding 'each' helps grasp how functional programming processes collections step-by-step before transforming or aggregating data.
Iterator Pattern in Software Design
'Each' is Ruby's built-in iterator method implementing this design pattern.
Knowing 'each' connects to the iterator pattern clarifies how objects expose sequential access to elements without exposing internal structure.
Assembly Line in Manufacturing
'Each' is like a station applying a task to every item on a conveyor belt.
Seeing iteration as an assembly line helps understand how repeated actions are applied systematically to items in order.
Common Pitfalls
#1Expecting 'each' to return a new collection with changes.
Wrong approach:[1, 2, 3].each { |n| n * 2 }
Correct approach:[1, 2, 3].map { |n| n * 2 }
Root cause:Confusing 'each' with 'map' and misunderstanding what 'each' returns.
#2Calling 'each' without a block and expecting iteration.
Wrong approach:[1, 2, 3].each
Correct approach:[1, 2, 3].each { |n| puts n }
Root cause:Not providing a block means no code runs on items; 'each' returns Enumerator instead.
#3Trying to stop 'each' early by returning false inside the block.
Wrong approach:[1, 2, 3].each { |n| break if n > 1 }
Correct approach:[1, 2, 3].each { |n| break if n > 1 }
Root cause:Actually, 'break' works to stop 'each', but returning false does not; misunderstanding control flow inside blocks.
Key Takeaways
'Each' is a simple, readable way to run code on every item in a Ruby collection.
It requires a block and returns the original collection, making it ideal for side effects, not transformations.
Understanding 'each' is foundational to working with Ruby collections and unlocking Enumerable methods.
Defining 'each' in your own classes makes them iterable and powerful.
Knowing when to use 'each' versus other iterators like 'map' or 'select' prevents common bugs.

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