liveBook · Manning

Substring

As explained in The Well-Grounded Rubyist, Fourth Edition

A substring is a contiguous sequence of characters extracted from a string or string-like value.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains indexes, lengths, ranges, searches, mutation, and regexp matching, while deferring detailed regular-expression syntax.
Examples
Uses irb examples for character indexes, ranges, literal and regexp searches, deletion, and replacement.
What it assumes
Assumes familiarity with strings and basic method calls while introducing indexes, ranges, and substring searches.
What you can do after
Apply it via Ruby's [], slice, slice!, and []= methods to inspect and edit string content.
How it connects
Connects strings with indexing, ranges, regular expressions, symbols, and string mutation.

Also explained in

Compare how 5 books explain substring →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.