0
0
Rubyprogramming~5 mins

String slicing and indexing in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AThe first 3 characters
BThe last 3 characters
CThe character at index 3
DAn error
How do you get the last character of a string str in Ruby?
Astr[-1]
Bstr[0]
Cstr[1]
Dstr[last]
What does str[1..4] return?
AAn error
BCharacters from index 1 to 3
CCharacters from index 0 to 4
DCharacters from index 1 to 4 inclusive
What happens if you do str[5, 10] but the string length is 8?
AReturns characters from index 5 to the end
BReturns an error
CReturns nil
DReturns the whole string
Which of these is NOT a valid way to slice a string in Ruby?
Astr[0, 3]
Bstr(1..4)
Cstr[-3..-1]
Dstr[2..5]
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.