Challenge - 5 Problems
Ruby Array Slicing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Ruby code using range slicing?
Consider the following Ruby code snippet. What will be printed?
Ruby
arr = [10, 20, 30, 40, 50] puts arr[1..3].inspect
Attempts:
2 left
💡 Hint
Remember that the range 1..3 includes elements at index 1, 2, and 3.
✗ Incorrect
The range 1..3 selects elements starting at index 1 up to and including index 3. So arr[1..3] returns [20, 30, 40].
❓ Predict Output
intermediate2:00remaining
What does this code output when slicing with an exclusive range?
Look at this Ruby code. What will it print?
Ruby
arr = ['a', 'b', 'c', 'd', 'e'] puts arr[0...3].inspect
Attempts:
2 left
💡 Hint
The three dots in the range exclude the last index.
✗ Incorrect
The range 0...3 includes indices 0, 1, and 2 but excludes 3. So arr[0...3] returns ["a", "b", "c"].
❓ Predict Output
advanced2:00remaining
What is the output of this code using negative indices in slicing?
Analyze this Ruby code and determine its output.
Ruby
arr = [1, 2, 3, 4, 5, 6] puts arr[-4..-2].inspect
Attempts:
2 left
💡 Hint
Negative indices count from the end: -1 is last element.
✗ Incorrect
Index -4 corresponds to element 3, -2 corresponds to element 5. The range -4..-2 includes indices -4, -3, -2, so elements [3, 4, 5].
❓ Predict Output
advanced2:00remaining
What error does this Ruby code raise when slicing with an invalid range?
What happens when you run this Ruby code?
Ruby
arr = [7, 8, 9] puts arr[5..7].inspect
Attempts:
2 left
💡 Hint
Check what Ruby returns when slicing beyond array length.
✗ Incorrect
Ruby returns nil when the start index of the range is beyond the array length. So arr[5..7] returns nil, not an error or empty array.
🧠 Conceptual
expert2:00remaining
How many elements are in the resulting array after this slicing?
Given this Ruby code, how many elements does the resulting array have?
Ruby
arr = (1..10).to_a result = arr[2..8] puts result.size
Attempts:
2 left
💡 Hint
Remember that the range 2..8 includes both ends.
✗ Incorrect
The slice arr[2..8] includes elements at indices 2 through 8, which is 7 elements total.