0
0
Rubyprogramming~20 mins

Why Ruby prefers iterators over loops - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Iterators Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
A1 2 3 1 2 3
B2 4 6
C2 4 6 2 4 6
DError: undefined method 'each' for Array
Attempts:
2 left
💡 Hint
Remember that both iterator and loop print doubled values for each element.
🧠 Conceptual
intermediate
1:30remaining
Why Ruby prefers iterators over loops?
Which reason best explains why Ruby prefers iterators over traditional loops?
ALoops are faster and more efficient than iterators in Ruby.
BIterators provide clearer, more readable code and reduce errors by handling loop control internally.
CIterators require more lines of code than loops.
DLoops automatically handle exceptions better than iterators.
Attempts:
2 left
💡 Hint
Think about code readability and error prevention.
🔧 Debug
advanced
1: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
ANameError: undefined local variable or method `n' for main:Object
BTypeError: no implicit conversion of nil into Integer
CNo error, prints doubled numbers and then prints last n
DSyntaxError: unexpected end-of-input
Attempts:
2 left
💡 Hint
Check variable scope outside the block.
Predict Output
advanced
2: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(', ')
A3, 6, 9, 2, 4, 6
B2, 4, 6, 3, 6, 9
C3, 6, 9
DError: undefined method 'join' for nil:NilClass
Attempts:
2 left
💡 Hint
Look at how elements are added to the result array.
🧠 Conceptual
expert
2:30remaining
Why iterators improve Ruby code maintainability
Which statement best explains how iterators improve maintainability in Ruby code compared to loops?
ALoops automatically optimize memory usage better than iterators.
BLoops allow more control over iteration, making code easier to maintain.
CIterators require explicit index management, increasing complexity.
DIterators encapsulate iteration logic, reducing boilerplate and making code easier to modify and less error-prone.
Attempts:
2 left
💡 Hint
Think about how code changes and errors relate to iteration style.