Bird
0
0

Which Ruby code snippet correctly uses reject to remove all odd numbers from an array numbers?

easy📝 Conceptual Q2 of 15
Ruby - Enumerable and Collection Processing
Which Ruby code snippet correctly uses reject to remove all odd numbers from an array numbers?
Anumbers.reject { |n| n % 2 == 0 }
Bnumbers.reject { |n| n.even? }
Cnumbers.reject(&:even?)
Dnumbers.reject { |n| n.odd? }
Step-by-Step Solution
Solution:
  1. Step 1: Identify the condition to reject

    We want to remove odd numbers, so the block should return true for odd numbers.
  2. Step 2: Analyze each option

    numbers.reject { |n| n.odd? } rejects elements where n.odd? is true, correctly removing odd numbers.
    numbers.reject { |n| n.even? } rejects even numbers, which is incorrect.
    numbers.reject(&:even?) uses reject(&:even?), which removes even numbers.
    numbers.reject { |n| n % 2 == 0 } rejects numbers divisible by 2 (even numbers), also incorrect.
  3. Final Answer:

    numbers.reject { |n| n.odd? } -> Option D
  4. Quick Check:

    Reject odd numbers by checking n.odd? [OK]
Quick Trick: Reject elements where condition is true [OK]
Common Mistakes:
  • Mixing up odd? and even? methods
  • Using reject with wrong condition
  • Assuming reject modifies original array

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes