Recall & Review
beginner
How do you access the first element of an array in Ruby?
Use the
first method. For example, array.first returns the first element.Click to reveal answer
beginner
What does
array[-1] return in Ruby?It returns the last element of the array. Negative indices count from the end, so
-1 is the last element.Click to reveal answer
beginner
How can you access the third element of an array named
arr?Use zero-based indexing:
arr[2] returns the third element because counting starts at zero.Click to reveal answer
beginner
What method returns the last element of an array in Ruby?
The
last method returns the last element. For example, array.last.Click to reveal answer
beginner
What happens if you try to access an index that is out of range in Ruby arrays?
Ruby returns
nil if the index is outside the array bounds, instead of an error.Click to reveal answer
Which Ruby code returns the first element of an array named
nums?✗ Incorrect
nums.first returns the first element. nums[1] returns the second element because indexing starts at zero.What does
arr[-2] return?✗ Incorrect
Negative indices count from the end.
-1 is last, so -2 is second from the end.How do you get the last element of an array
list?✗ Incorrect
list.last returns the last element of the array.What will
array[10] return if array has only 5 elements?✗ Incorrect
Ruby returns
nil when accessing an index outside the array bounds.Which index accesses the third element in a Ruby array?
✗ Incorrect
Ruby arrays use zero-based indexing, so index 2 is the third element.
Explain how to access the first, last, and a specific element in a Ruby array.
Think about methods and index numbers.
You got /4 concepts.
What happens if you try to access an array element with an index that is too large?
Consider Ruby's behavior with out-of-range indices.
You got /3 concepts.