Bird
0
0

Given an array arr = [1, 2, 3, 4, 5], which Ruby code correctly creates a new array with only even numbers?

hard📝 Application Q15 of 15
Ruby - Arrays
Given an array arr = [1, 2, 3, 4, 5], which Ruby code correctly creates a new array with only even numbers?
Anew_arr = arr.map { |num| num * 2 }
Bnew_arr = arr.push(2, 4)
Cnew_arr = arr.delete_if { |num| num.even? }
Dnew_arr = arr.select { |num| num % 2 == 0 }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    We want a new array containing only even numbers from the original array.
  2. Step 2: Analyze each option

    new_arr = arr.select { |num| num % 2 == 0 } uses 'select' to filter even numbers correctly. new_arr = arr.map { |num| num * 2 } doubles all numbers, not filtering. new_arr = arr.delete_if { |num| num.even? } deletes even numbers, opposite of goal. new_arr = arr.push(2, 4) adds 2 and 4 to original array, not filtering.
  3. Final Answer:

    new_arr = arr.select { |num| num % 2 == 0 } -> Option D
  4. Quick Check:

    Use 'select' to filter arrays [OK]
Quick Trick: Use 'select' to pick items matching a condition [OK]
Common Mistakes:
MISTAKES
  • Using 'map' instead of 'select' for filtering
  • Deleting instead of selecting items
  • Adding items instead of filtering

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes