0
0
Rubyprogramming~5 mins

Accessing elements (indexing, first, last) in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Anums[1]
Bnums.first
Cnums.last
Dnums[-1]
What does arr[-2] return?
ASecond element from the end
BFirst element
CLast element
DSecond element from the start
How do you get the last element of an array list?
Alist.last
Blist.first
Clist[0]
Dlist[1]
What will array[10] return if array has only 5 elements?
AThe 11th element
BAn error
CThe last element
Dnil
Which index accesses the third element in a Ruby array?
A1
B3
C2
D-3
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.