Bird
0
0

How can you extract a slice from arr = [1, 3, 5, 7, 9, 11] that includes every second element from index 0 to 5?

hard📝 Application Q9 of 15
Ruby - Arrays
How can you extract a slice from arr = [1, 3, 5, 7, 9, 11] that includes every second element from index 0 to 5?
Aarr[0..5].step(2).to_a
Barr[0..5].select.with_index { |_, i| i.even? }
Carr[0...6].select.with_index { |_, i| i % 2 == 1 }
Darr[0..5].filter.with_index { |_, i| i % 2 == 1 }
Step-by-Step Solution
Solution:
  1. Step 1: Slice the array from index 0 to 5

    Use arr[0..5] to get elements at indices 0 through 5.
  2. Step 2: Select elements at even indices within the slice

    Use select.with_index and check for even indices to get every second element.
  3. Final Answer:

    arr[0..5].select.with_index { |_, i| i.even? } -> Option B
  4. Quick Check:

    Use select.with_index to filter elements by index parity [OK]
Quick Trick: Use select.with_index to filter elements by index [OK]
Common Mistakes:
  • Using step on array slice (step is for ranges)
  • Filtering odd indices instead of even
  • Using wrong range end index

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes