Bird
0
0

Which Ruby code correctly creates a new array containing only the odd numbers from the original array?

hard📝 Application Q8 of 15
Ruby - Arrays
Which Ruby code correctly creates a new array containing only the odd numbers from the original array?
numbers = [10, 15, 20, 25, 30]
Aodd_numbers = numbers.delete_if { |n| n.odd? }
Bodd_numbers = numbers.reject { |n| n.odd? }
Codd_numbers = numbers.map { |n| n if n.even? }
Dodd_numbers = numbers.select { |n| n.odd? }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    We want a new array with only odd numbers from the original.
  2. Step 2: Analyze options

    odd_numbers = numbers.select { |n| n.odd? } uses 'select' with 'odd?' which filters and keeps odd numbers correctly.
  3. Step 3: Why others are wrong

    odd_numbers = numbers.reject { |n| n.odd? } rejects odd numbers (keeps even), C maps but returns nil for even numbers, D deletes odd numbers from original array (modifies in place).
  4. Final Answer:

    odd_numbers = numbers.select { |n| n.odd? } -> Option D
  5. Quick Check:

    'select' filters elements based on condition [OK]
Quick Trick: Use 'select' with condition to filter arrays [OK]
Common Mistakes:
MISTAKES
  • Using 'reject' instead of 'select' for filtering
  • Using 'map' which transforms but doesn't filter
  • Modifying original array instead of creating new

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes