Recall & Review
beginner
What does string indexing mean in Ruby?
String indexing means accessing a single character in a string by its position number, starting from 0 for the first character.
Click to reveal answer
beginner
How do you get the first 5 characters of a string in Ruby?
You can use slicing like this:
str[0, 5] which means start at index 0 and take 5 characters.Click to reveal answer
intermediate
What does negative indexing do in Ruby strings?
Negative indexing counts from the end of the string. For example,
str[-1] gives the last character.Click to reveal answer
beginner
How to slice a string from index 2 to index 6 in Ruby?
Use
str[2..6] which includes characters from index 2 up to 6, inclusive.Click to reveal answer
intermediate
What happens if you try to slice beyond the string length in Ruby?
Ruby returns as many characters as possible without error. For example,
str[0, 100] returns the whole string if it is shorter than 100 characters.Click to reveal answer
What does
str[3] return in Ruby?✗ Incorrect
str[3] returns the single character at position 3 (fourth character) in the string.How do you get the last character of a string
str in Ruby?✗ Incorrect
Negative index
-1 accesses the last character in Ruby strings.What does
str[1..4] return?✗ Incorrect
The range
1..4 includes both ends, so characters at indexes 1, 2, 3, and 4 are returned.What happens if you do
str[5, 10] but the string length is 8?✗ Incorrect
Ruby returns characters from index 5 to the end without error, even if 10 characters are requested.
Which of these is NOT a valid way to slice a string in Ruby?
✗ Incorrect
str(1..4) is not valid syntax for slicing strings in Ruby.Explain how to access a single character and a substring in Ruby strings using indexing and slicing.
Think about how you get one letter vs. a group of letters.
You got /4 concepts.
Describe how negative indexing works in Ruby strings and give an example.
Negative numbers start counting backwards from the last character.
You got /3 concepts.