Bird
0
0

How do you correctly create a lazy enumerator from the array [2, 4, 6] in Ruby?

easy📝 Syntax Q3 of 15
Ruby - Functional Patterns in Ruby
How do you correctly create a lazy enumerator from the array [2, 4, 6] in Ruby?
A[2, 4, 6].lazy_enum
B[2, 4, 6].to_enum.lazy
CLazyEnumerator.new([2, 4, 6])
D[2, 4, 6].lazy
Step-by-Step Solution
Solution:
  1. Step 1: Understand Ruby's lazy enumerator creation

    Ruby provides the .lazy method directly on Enumerable objects to create lazy enumerators.
  2. Step 2: Check each option

    • [2, 4, 6].lazy is the correct syntax.
    • [2, 4, 6].to_enum.lazy is redundant but valid; however, to_enum returns an Enumerator, so chaining .lazy works but is unnecessary.
    • LazyEnumerator.new([2, 4, 6]) is invalid as LazyEnumerator is not a Ruby class.
    • [2, 4, 6].lazy_enum is invalid; no such method exists.
  3. Final Answer:

    [2, 4, 6].lazy -> Option D
  4. Quick Check:

    Directly call .lazy on the array [OK]
Quick Trick: Use .lazy directly on the enumerable [OK]
Common Mistakes:
  • Using non-existent methods like .lazy_enum
  • Trying to instantiate LazyEnumerator class
  • Unnecessarily chaining .to_enum before .lazy

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes