Each for iteration in Ruby - Time & Space Complexity
We want to understand how the time it takes to run a Ruby each loop changes as the list gets bigger.
How does the number of steps grow when we use each to go through items?
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 each loop runs once for every item in the list.
- How many times: Exactly as many times as there are items in the array.
As the list gets bigger, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times |
| 100 | 100 times |
| 1000 | 1000 times |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items.
[X] Wrong: "The each loop runs a fixed number of times no matter the list size."
[OK] Correct: The loop runs once for every item, so if the list grows, the loop runs more times.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how programs handle bigger data.
"What if we nested one each loop inside another? How would the time complexity change?"
Practice
each method do in Ruby when used with an array?Solution
Step 1: Understand the purpose of
Theeacheachmethod is used to loop over every element in a collection like an array.Step 2: Identify what happens inside the block
The block given toeachruns once for each element, allowing actions on each item.Final Answer:
It runs the given block once for every element in the array. -> Option BQuick Check:
eachrepeats actions per item [OK]
- Confusing each with sorting or filtering methods
- Thinking each returns a new array
- Assuming each counts elements
numbers using each in Ruby?Solution
Step 1: Recognize correct
Theeachsyntaxeachmethod is called on the array, followed by a block with a parameter inside pipes.Step 2: Check block format
numbers.each { |num| puts num } uses curly braces with a block parameter|num|and a valid block bodyputs num.Final Answer:
numbers.each { |num| puts num } -> Option CQuick Check:
Correct block syntax = numbers.each { |num| puts num } [OK]
- Placing the variable outside the pipes
- Calling each without a block
- Using parentheses incorrectly with each
fruits = ['apple', 'banana', 'cherry'] fruits.each do |fruit| puts fruit.upcase end
Solution
Step 1: Understand the each loop behavior
The code loops over each fruit and prints the uppercase version usingputs fruit.upcase.Step 2: Determine output format
putsprints each string on a new line, so each fruit name appears uppercase on its own line.Final Answer:
APPLE BANANA CHERRY -> Option AQuick Check:
each + puts prints each item on a new line [OK]
- Expecting output on one line
- Confusing puts with print
- Not applying upcase method
numbers = [1, 2, 3] numbers.each do num puts num * 2 end
Solution
Step 1: Check block variable syntax
In Ruby, block variables must be enclosed in pipes like|num|when usingdo...end.Step 2: Identify the missing pipes
The code usesdo numinstead ofdo |num|, causing a syntax error.Final Answer:
Missing pipes around the block variable 'num'. -> Option AQuick Check:
Block variables need pipes |var| [OK]
- Omitting pipes around block variables
- Thinking parentheses are required after each
- Believing puts cannot be used inside blocks
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 hash iteration with each
When iterating a hash witheach, two block variables receive the key and value respectively.Step 2: Use correct variable order and string formatting
scores.each do |name, score| puts "#{name.capitalize}: #{score}" end correctly uses|name, score|and prints with#{name.capitalize}: #{score}.Final Answer:
scores.each do |name, score| puts "#{name.capitalize}: #{score}" end -> Option DQuick Check:
Hash each uses two vars: key, value [OK]
- Swapping key and value variables
- Using only one block variable for hash
- Not capitalizing the name correctly
Ready to prove it?
Pass the test and this pattern moves unknown
