0
0
Rubyprogramming~20 mins

Accessing elements (indexing, first, last) in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Array Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of accessing the first and last elements?
Consider the Ruby array arr = [10, 20, 30, 40, 50]. What will be printed by the following code?
puts arr.first
puts arr.last
Ruby
arr = [10, 20, 30, 40, 50]
puts arr.first
puts arr.last
A10\n10
B50\n10
C10\n50
D50\n50
Attempts:
2 left
💡 Hint
Remember, first gives the first element and last gives the last element of an array.
Predict Output
intermediate
2:00remaining
What is the output of negative indexing in Ruby arrays?
Given the array nums = [5, 10, 15, 20, 25], what will puts nums[-2] print?
Ruby
nums = [5, 10, 15, 20, 25]
puts nums[-2]
A15
B20
C25
D10
Attempts:
2 left
💡 Hint
Negative indices count from the end of the array, starting at -1 for the last element.
Predict Output
advanced
2:00remaining
What happens when accessing an out-of-range index?
What will the following Ruby code print?
arr = [1, 2, 3]
puts arr[5].inspect
Ruby
arr = [1, 2, 3]
puts arr[5].inspect
Anil
BIndexError
C3
D0
Attempts:
2 left
💡 Hint
Ruby returns nil when you access an index outside the array bounds.
Predict Output
advanced
2:00remaining
What is the output when using first(n) and last(n) methods?
Given arr = [7, 14, 21, 28, 35], what will the following code print?
p arr.first(3)
p arr.last(2)
Ruby
arr = [7, 14, 21, 28, 35]
p arr.first(3)
p arr.last(2)
A[7, 14]\n[28, 35]
B[7, 14, 21]\n[21, 28]
C[14, 21, 28]\n[28, 35]
D[7, 14, 21]\n[28, 35]
Attempts:
2 left
💡 Hint
The first(n) method returns the first n elements, and last(n) returns the last n elements.
🧠 Conceptual
expert
3:00remaining
What is the value of result after this code runs?
Consider this Ruby code:
arr = ['a', 'b', 'c', 'd']
result = arr[-1] + arr[0] + arr[-3]

What is the value of result?
Ruby
arr = ['a', 'b', 'c', 'd']
result = arr[-1] + arr[0] + arr[-3]
A"dab"
B"d a b"
C"dcb"
D"dac"
Attempts:
2 left
💡 Hint
Remember that negative indices count from the end: -1 is last, -2 is second last, etc.