liveBook · Manning

[]

As explained in The Well-Grounded Rubyist, Fourth Edition

[] is a Ruby String method that retrieves characters or substrings using indexes, ranges, strings, or regular expressions.

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.

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains multiple argument forms and mutation aliases, while deferring regular-expression details to a later treatment.
Examples
Uses Ruby is a cool language. to demonstrate indexes, ranges, substring searches, regular expressions, removal, and replacement.
What you can do after
Apply [] to extract, search, replace, or remove selected portions of a Ruby string.
How it connects
Connects String [] with ranges, regular expressions, slice, slice!, and []= replacement.

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.