Ruby’s String [] method retrieves characters and substrings. Pass a zero-origin integer index for one character; use a negative index to count backward from the end. section 8.1.2
Use different argument forms to control what [] finds:
- An index and length return a substring beginning at the index. section 8.1.2
- A range selects an inclusive or exclusive span; negative range endpoints count from the end and still proceed left to right. section 8.1.2
- A string searches for an explicit substring, returning the match or nil when it is absent. section 8.1.2
- A regular expression searches by pattern, making [] more than simple positional indexing. section 8.1.2
Retrieving and changing text
With string = "Ruby is a cool language.", string[5, 10] returns "is a cool ", while string["cool"] returns "cool". The related []= method accepts the same indexing forms and replaces the selected text: string["cool"] = "great" changes the sentence to "Ruby is a great language.". The slice alias retrieves the same way, and slice! removes the matched text from the original string.
