A substring is a contiguous sequence of characters extracted from a string. In Ruby, the [] method retrieves characters or substrings using zero-based indexes, lengths, ranges, literal searches, or regular expressions. section 8.1.2
Ruby supports several ways to retrieve and modify substrings:
- Use an integer to retrieve one character, including negative indexes counted from the end. section 8.1.2
- Use an index and length, such as string[5, 10], to retrieve a fixed number of characters. section 8.1.2
- Use an inclusive or exclusive range, such as string[7...14], to select a span from left to right. section 8.1.2
- Search with a literal substring or regular expression; a successful match returns text, while an unsuccessful literal search returns nil. section 8.1.2 section 11.1
- Use slice as an alias for [], slice! to remove matched characters, and []= to replace selected text in place. section 8.1.2
Extracting and changing text
Given string = "Ruby is a cool language.", string[5, 10] returns "is a cool "; string["cool"] = "great" changes the receiver to "Ruby is a great language." Negative indexes and ranges can similarly target text near the end. section 8.1.2
>> string = "Ruby is a cool language."
=> "Ruby is a cool language."
>> string[5]
=> "i"
>> string[-12]
=> "o"
Inspect zero-based and negative indexing directly with a short irb example. section 8.1.2
Regular expressions broaden substring selection from exact text to character patterns. They can locate matching portions, scan for multiple occurrences, substitute text, or split strings, although their patterns may be difficult to read and maintain. section 11.0 section 11.1




