Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
String#=~
(::Regexp regex) -> ::Integer?
[T] (::String::_MatchAgainst[self, T] object) -> T
self =~ other → integer or nil
string.c
View on GitHub ↗
static VALUE
rb_str_match(VALUE x, VALUE y)
{
switch (OBJ_BUILTIN_TYPE(y)) {
case T_STRING:
rb_raise(rb_eTypeError, "type mismatch: String given");
case T_REGEXP:
return rb_reg_match(y, x);
default:
return rb_funcall(y, idEqTilde, 1, x);
}
}
When other is a Regexp:
-
Returns the integer index (in characters) of the first match for
selfandother, ornilif none; -
Updates Regexp-related global variables.
Examples:
Example
'foo' =~ /f/ # => 0 $~ # => #<MatchData "f"> 'foo' =~ /o/ # => 1 $~ # => #<MatchData "o"> 'foo' =~ /x/ # => nil $~ # => nil
Note that string =~ regexp is different from regexp =~ string (see Regexp#=~):
Example
number = nil 'no. 9' =~ /(?<number>\d+)/ # => 4 number # => nil # Not assigned. /(?<number>\d+)/ =~ 'no. 9' # => 4 number # => "9" # Assigned.
When other is not a Regexp, returns the value returned by other =~ self.
Related: see Querying.