Bird
0
0

Why does arr[-1] return the last element in Ruby arrays?

hard📝 Conceptual Q10 of 15
Ruby - Arrays
Why does arr[-1] return the last element in Ruby arrays?
ABecause negative indexes count from the end backwards
BBecause Ruby arrays are reversed internally
CBecause -1 is treated as 0 internally
DBecause arr[-1] is an alias for arr.first
Step-by-Step Solution
Solution:
  1. Step 1: Understand negative indexing in Ruby

    Negative indexes count from the end: -1 is last element, -2 second last, etc.
  2. Step 2: Clarify why arr[-1] returns last element

    Ruby uses this indexing to allow easy access to elements from the end.
  3. Final Answer:

    Because negative indexes count from the end backwards -> Option A
  4. Quick Check:

    Negative index -1 = last element [OK]
Quick Trick: Negative indexes count backward from array end [OK]
Common Mistakes:
MISTAKES
  • Thinking arrays are reversed internally
  • Believing -1 equals 0
  • Confusing arr[-1] with arr.first

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes