Bird
0
0

How can you safely access the last element of an array arr that might be empty, without causing an error?

hard📝 Application Q9 of 15
Ruby - Arrays
How can you safely access the last element of an array arr that might be empty, without causing an error?
AUse arr[-1] which raises error if empty
BUse arr.last which returns nil if empty
CUse arr[arr.length] to get last element
DUse arr.first if arr.empty?
Step-by-Step Solution
Solution:
  1. Step 1: Understand behavior of arr.last on empty array

    arr.last returns nil if the array is empty, no error occurs.
  2. Step 2: Compare with other options

    arr[-1] returns nil too, but arr[arr.length] is out of range and returns nil; arr.first if arr.empty? is unrelated.
  3. Final Answer:

    Use arr.last which returns nil if empty -> Option B
  4. Quick Check:

    arr.last safely returns nil on empty array [OK]
Quick Trick: arr.last returns nil safely even if array is empty [OK]
Common Mistakes:
  • Thinking arr[-1] raises error
  • Using arr[arr.length] which is out of range
  • Confusing first and last methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes