Bird
0
0

How can you swap the first and last elements of an array arr in Ruby using a single line?

hard📝 Application Q9 of 15
Ruby - Hashes
How can you swap the first and last elements of an array arr in Ruby using a single line?
Aarr[0], arr[-1] = arr[-1], arr[0]
Barr.swap(0, -1)
Carr[0] = arr[-1]; arr[-1] = arr[0]
Darr[0] == arr[-1]
Step-by-Step Solution
Solution:
  1. Step 1: Understand parallel assignment in Ruby

    Ruby allows swapping values in one line using parallel assignment.
  2. Step 2: Apply swap syntax for first and last elements

    Use arr[0], arr[-1] = arr[-1], arr[0] to swap first and last elements.
  3. Final Answer:

    arr[0], arr[-1] = arr[-1], arr[0] -> Option A
  4. Quick Check:

    Parallel assignment swaps values in one line [OK]
Quick Trick: Use parallel assignment to swap array elements [OK]
Common Mistakes:
  • Using non-existent swap method
  • Assigning sequentially causing overwrite
  • Using == instead of =

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes