Challenge - 5 Problems
Ruby Array Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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
Attempts:
2 left
💡 Hint
Remember,
first gives the first element and last gives the last element of an array.✗ Incorrect
The
first method returns the first element (10), and last returns the last element (50). So the output is 10 then 50 on separate lines.❓ Predict Output
intermediate2: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]
Attempts:
2 left
💡 Hint
Negative indices count from the end of the array, starting at -1 for the last element.
✗ Incorrect
Index -1 is the last element (25), so -2 is the second last element (20).
❓ Predict Output
advanced2: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
Attempts:
2 left
💡 Hint
Ruby returns nil when you access an index outside the array bounds.
✗ Incorrect
Accessing an index beyond the array length returns nil instead of an error.
❓ Predict Output
advanced2: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)
Attempts:
2 left
💡 Hint
The
first(n) method returns the first n elements, and last(n) returns the last n elements.✗ Incorrect
The first 3 elements are [7, 14, 21], and the last 2 elements are [28, 35].
🧠 Conceptual
expert3:00remaining
What is the value of
result after this code runs?Consider this Ruby code:
What is the value of
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]
Attempts:
2 left
💡 Hint
Remember that negative indices count from the end: -1 is last, -2 is second last, etc.
✗ Incorrect
arr[-1] is 'd', arr[0] is 'a', arr[-3] is 'b'. Concatenating gives 'd' + 'a' + 'b' = "dab".