Each as the primary iterator in Ruby - Time & Space Complexity
When we use each to go through items in a list, it's important to know how the time it takes grows as the list gets bigger.
We want to find out how the number of steps changes when the list size changes.
Analyze the time complexity of the following code snippet.
numbers = [1, 2, 3, 4, 5]
numbers.each do |num|
puts num * 2
end
This code goes through each number in the list and prints double its value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
eachloop goes through every item in the list once. - How many times: It runs exactly as many times as there are items in the list.
As the list gets bigger, the number of steps grows in a straight line with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps (one per item) |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: Doubling the list size doubles the work done.
Time Complexity: O(n)
This means the time it takes grows directly in proportion to the number of items in the list.
[X] Wrong: "Using each is always slow because it loops over everything multiple times."
[OK] Correct: Actually, each goes through the list only once, so it's as fast as it can be for checking every item.
Understanding how each works helps you explain how your code handles lists efficiently, a skill that shows you know how to think about performance.
"What if we nested one each loop inside another? How would the time complexity change?"
Practice
each method do in Ruby when used on an array?Solution
Step 1: Understand the purpose of
Theeacheachmethod is used to run a block of code for every item in a collection like an array.Step 2: Check what
It does not change or sort the array; it simply processes each item one by one.eachdoes to the arrayFinal Answer:
It runs a block of code once for every item in the array. -> Option BQuick Check:
eachruns code on each item [OK]
each processes items, does not change array [OK]- Thinking
eachmodifies the array - Confusing
eachwith methods likemap - Assuming
eachreturns a new array
each on an array numbers to print each number?Solution
Step 1: Identify correct block syntax with
The correct syntax useseacheachfollowed by a block with{ |variable| ... }ordo |variable| ... end.Step 2: Check each option
numbers.each { |num| puts num } usesnumbers.each { |num| puts num }which is correct. Others have syntax errors or wrong order.Final Answer:
numbers.each { |num| puts num } -> Option CQuick Check:
Correct block syntax = numbers.each { |num| puts num } [OK]
each { |item| ... } or each do |item| ... end [OK]- Writing
each numbersinstead ofnumbers.each - Missing block delimiters like braces or do-end
- Not using pipes
| |around block variable
fruits = ['apple', 'banana', 'cherry']
fruits.each { |fruit| puts fruit.upcase }Solution
Step 1: Understand what
Theeachdoes withputs fruit.upcaseeachmethod runs the block for each fruit, printing the uppercase version.Step 2: Check output line by line
It prints 'APPLE', then 'BANANA', then 'CHERRY' each on a new line.Final Answer:
APPLE BANANA CHERRY -> Option AQuick Check:
eachprints uppercase fruits [OK]
puts prints each item on a new line [OK]- Thinking
eachreturns a new array - Expecting lowercase output
- Confusing
putswith returning a list
items = [1, 2, 3] items.each do item puts item * 2 end
Solution
Step 1: Check block variable syntax in
When usingeach doblockdowitheach, the block variable must be inside pipes:do |item|.Step 2: Identify the error
The code misses pipes arounditem, causing a syntax error.Final Answer:
Missing pipes around block variable: should be|item|-> Option DQuick Check:
Block variables need pipes| |[OK]
| | with each do [OK]- Omitting pipes around block variables
- Thinking
dois invalid witheach - Assuming multiplication inside
eachis wrong
scores = { alice: 10, bob: 15, carol: 12 }, how can you use each to print each name and score in the format Name: Score?Solution
Step 1: Understand
When usingeachon a hasheachon a hash, the block receives two variables: key and value.Step 2: Match variables and format output
The key is the name (symbol), value is the score. Usename.capitalizeto print the name nicely.Final Answer:
scores.each { |name, score| puts "#{name.capitalize}: #{score}" } -> Option AQuick Check:
Hasheachuses key, value pairs [OK]
each block gets two vars: key and value [OK]- Swapping key and value variables
- Using only one block variable for hash
- Trying to capitalize a number
Ready to prove it?
Pass the test and this pattern moves unknown
