DEV Community

Burdette Lamar
Burdette Lamar

Posted on

Ruby Method of the Day: String#=~

Method String#=~ searches string self, looking for the given argument (Regexp or other object).

When the argument is a regexp, the method returns the integer index of the first substring that matches the regexp, or nil if no match.

But that's only the beginning. The method also sets a number of global variables that give more details:

  • $~: Returns a MatchData object, or nil.
  • $&: Returns the matched part of the string, or nil.
  • $`: Returns the part of the string to the left of the match, or nil.
  • $': Returns the part of the string to the right of the match, or nil.
  • $+: Returns the last group matched, or nil.
  • $1, $2, etc.: Returns the first, second, etc., matched group, or nil. Note that $0 is quite different; it returns the name of the currently executing program.

See examples at Regexp Global Variables.

[Yes, I've copied shamelessly from the official documentation for regexp global variables. But I don't feel bad; I wrote that documentation (as well as the documentation for String#=~).]

More methods at #rubymethodoftheday.

Top comments (0)