Bird
0
0

Given a large array arr = (1..1000000).to_a, which Ruby code snippet efficiently finds the first 3 even numbers greater than 500000 using lazy enumerators?

hard📝 Application Q15 of 15
Ruby - Functional Patterns in Ruby
Given a large array arr = (1..1000000).to_a, which Ruby code snippet efficiently finds the first 3 even numbers greater than 500000 using lazy enumerators?
Aarr.lazy.select { |x| x > 500000 && x.even? }.first(3)
Barr.select { |x| x > 500000 && x.even? }.first(3)
Carr.lazy.map { |x| x * 2 }.first(3)
Darr.take(3).lazy.select(&:even?)
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal and data size

    We want the first 3 even numbers greater than 500,000 from a large array. Using lazy enumerators avoids processing the entire array.
  2. Step 2: Analyze each option

    arr.lazy.select { |x| x > 500000 && x.even? }.first(3) uses lazy, filters with select for the condition, then takes first 3 - efficient and correct.
    arr.select { |x| x > 500000 && x.even? }.first(3) processes entire array eagerly, inefficient.
    arr.lazy.map { |x| x * 2 }.first(3) maps all elements, not filtering by condition.
    arr.take(3).lazy.select(&:even?) takes first 3 elements then filters, which misses numbers > 500,000.
  3. Final Answer:

    arr.lazy.select { |x| x > 500000 && x.even? }.first(3) -> Option A
  4. Quick Check:

    Lazy select with condition then first(3) = C [OK]
Quick Trick: Use lazy select with condition, then first(n) for efficiency [OK]
Common Mistakes:
  • Using eager select causing slow processing
  • Filtering after taking first 3 elements incorrectly
  • Using map instead of select for filtering

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes