Challenge - 5 Problems
Ruby Iterators Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of iterator vs loop in Ruby
What is the output of this Ruby code using an iterator and a loop?
Ruby
arr = [1, 2, 3] # Using iterator arr.each { |x| print x * 2, ' ' } # Using loop count = 0 while count < arr.size print arr[count] * 2, ' ' count += 1 end
Attempts:
2 left
💡 Hint
Remember that both iterator and loop print doubled values for each element.
✗ Incorrect
The iterator 'each' and the while loop both print each element doubled. The output shows doubled values twice because both methods print in sequence.
🧠 Conceptual
intermediate1:30remaining
Why Ruby prefers iterators over loops?
Which reason best explains why Ruby prefers iterators over traditional loops?
Attempts:
2 left
💡 Hint
Think about code readability and error prevention.
✗ Incorrect
Ruby favors iterators because they make code easier to read and maintain. They also manage loop control internally, reducing common mistakes like infinite loops.
🔧 Debug
advanced1:30remaining
Identify the error in this iterator usage
What error does this Ruby code produce?
Ruby
numbers = [1, 2, 3] numbers.each do |n| puts n * 2 end puts n
Attempts:
2 left
💡 Hint
Check variable scope outside the block.
✗ Incorrect
The variable 'n' is only defined inside the block passed to 'each'. Trying to use it outside causes a NameError.
❓ Predict Output
advanced2:00remaining
Output difference between iterator and manual loop
What is the output of this Ruby code?
Ruby
arr = [1, 2, 3] result = [] arr.each { |x| result << x * 3 } index = 0 while index < arr.size result << arr[index] * 2 index += 1 end puts result.join(', ')
Attempts:
2 left
💡 Hint
Look at how elements are added to the result array.
✗ Incorrect
The iterator adds tripled values first, then the loop adds doubled values. The final array has tripled values followed by doubled values.
🧠 Conceptual
expert2:30remaining
Why iterators improve Ruby code maintainability
Which statement best explains how iterators improve maintainability in Ruby code compared to loops?
Attempts:
2 left
💡 Hint
Think about how code changes and errors relate to iteration style.
✗ Incorrect
Iterators hide the details of iteration, so developers write less code and avoid common mistakes like off-by-one errors, making maintenance simpler.