DEV Community

Burdette Lamar
Burdette Lamar

Posted on

1 1 1 1 1

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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs