0
0
Rubyprogramming~20 mins

Lazy enumerators in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Lazy Enumerator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of lazy enumerator with chained operations
What is the output of this Ruby code using lazy enumerators?
Ruby
result = (1..Float::INFINITY).lazy.select { |x| x % 3 == 0 }.map { |x| x * 2 }.first(5)
puts result.inspect
A[1, 2, 3, 4, 5]
B[3, 6, 9, 12, 15]
C[2, 4, 6, 8, 10]
D[6, 12, 18, 24, 30]
Attempts:
2 left
💡 Hint
Remember that lazy enumerators only compute values as needed and the select filters multiples of 3.
🧠 Conceptual
intermediate
1:30remaining
Behavior of lazy enumerators with infinite sequences
Which statement best describes how Ruby's lazy enumerators handle infinite sequences?
AThey cannot be used with infinite sequences.
BThey compute elements only when needed, avoiding infinite loops.
CThey compute all elements at once, causing memory overflow.
DThey always return an array immediately.
Attempts:
2 left
💡 Hint
Think about how lazy evaluation delays computation.
🔧 Debug
advanced
1:30remaining
Identify the error in lazy enumerator chaining
What error does this Ruby code raise?
Ruby
result = (1..10).lazy.map { |x| x * 2 }.select { |x| x > 10 }
puts result
ARuntimeError: infinite loop detected
BTypeError: no implicit conversion of nil into Integer
CNo error, prints a lazy enumerator object
DArgumentError: wrong number of arguments (given 0, expected 1)
Attempts:
2 left
💡 Hint
Printing a lazy enumerator does not execute it.
Predict Output
advanced
2:00remaining
Output of lazy enumerator with take and map
What is the output of this Ruby code?
Ruby
result = (1..Float::INFINITY).lazy.map { |x| x * x }.take(4).force
puts result.inspect
A[1, 4, 9, 16]
B[1, 2, 3, 4]
C[1, 8, 27, 64]
D[2, 4, 6, 8]
Attempts:
2 left
💡 Hint
The map squares each number, take limits to first 4, force evaluates the lazy enumerator.
📝 Syntax
expert
1:30remaining
Which option causes a syntax error with lazy enumerators?
Which of these Ruby code snippets will cause a syntax error?
A(1..10).lazy.select { |x| x.even? }.map ->(x) { x * 3 }
B(1..10).lazy.select { |x| x.even? }.map { |x| x * 3 }
C(1..10).lazy.select { |x| x.even? }.map { |x| x * 3 }.force
D(1..10).lazy.select { |x| x.even? }.map { |x| x * 3 }.first(3)
Attempts:
2 left
💡 Hint
Check the syntax of the block passed to map.