Bird
0
0

Given arr = [2, 4, 6, 8, 10, 12], which expression returns a new array with every second element starting from index 1 up to index 5?

hard📝 Application Q15 of 15
Ruby - Arrays
Given arr = [2, 4, 6, 8, 10, 12], which expression returns a new array with every second element starting from index 1 up to index 5?
Aarr[1..5].select.with_index { |_, i| i.even? }
Barr[1..5].select.with_index { |_, i| i.odd? }
Carr[1...6].values_at(*arr[1...6].each_index.select(&:even?))
Darr[1..5].values_at(*arr[1..5].each_index.select(&:odd?))
Step-by-Step Solution
Solution:
  1. Step 1: Slice array from index 1 to 5

    arr[1..5] gives [4, 6, 8, 10, 12].
  2. Step 2: Select every second element starting from index 1 of the slice

    Indexes inside the slice are 0 to 4. Selecting odd indexes (1, 3) gives elements 6 and 10.
  3. Step 3: Check options for correct syntax and output

    arr[1..5].values_at(*arr[1..5].each_index.select(&:odd?)) uses values_at with odd indexes on the slice correctly, returning [6, 10].
  4. Final Answer:

    arr[1..5].values_at(*arr[1..5].each_index.select(&:odd?)) -> Option D
  5. Quick Check:

    Use values_at with odd indexes on slice for every second element [OK]
Quick Trick: Use values_at with selected indexes for custom slicing [OK]
Common Mistakes:
  • Confusing odd/even indexes inside the slice
  • Using select without values_at returns elements, not indexes
  • Using wrong range operator causing off-by-one errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes