Challenge - 5 Problems
Ruby String Slicing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of negative index slicing
What is the output of this Ruby code?
Ruby
str = "programming" puts str[-4, 3]
Attempts:
2 left
💡 Hint
Remember that negative index counts from the end, and the second number is length.
✗ Incorrect
str[-4, 3] starts 4 characters from the end ('m') and takes 3 characters: 'm', 'm', 'i'.
❓ Predict Output
intermediate2:00remaining
Output of range slicing
What will this Ruby code print?
Ruby
text = "hello world" puts text[2..5]
Attempts:
2 left
💡 Hint
Range includes both start and end indices.
✗ Incorrect
text[2..5] extracts characters at indices 2,3,4,5: 'l','l','o',' '.
🔧 Debug
advanced2:00remaining
Identify the error in slicing
What error does this Ruby code raise?
Ruby
word = "example" puts word[3, -2]
Attempts:
2 left
💡 Hint
Negative length in slice returns nil instead of error.
✗ Incorrect
In Ruby, a negative length in slice returns nil, no error is raised.
❓ Predict Output
advanced2:00remaining
Output of slice with range and negative indices
What is the output of this Ruby code?
Ruby
s = "abcdefg" puts s[-5..-3]
Attempts:
2 left
💡 Hint
Negative indices count from the end, inclusive range.
✗ Incorrect
s[-5..-3] means indices 2 to 4: 'c','d','e'.
🧠 Conceptual
expert2:00remaining
Number of characters extracted by slice
How many characters does this Ruby slice extract?
Ruby
str = "university" result = str[1, 4]
Attempts:
2 left
💡 Hint
The second argument is the length of the slice.
✗ Incorrect
str[1,4] extracts 4 characters starting at index 1.