End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
String#=~
string =~ regexp → integer or nil
string =~ object → 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);
}
}
Returns the Integer index of the first substring that matches the given regexp, or nil if no match found:
Example
'foo' =~ /f/ # => 0 'foo' =~ /o/ # => 1 'foo' =~ /x/ # => nil
Note: also updates Regexp-related global variables.
If the given object is not a Regexp, returns the value returned by object =~ self.
Note that string =~ regexp is different from regexp =~ string (see Regexp#=~):
Example
number= nil "no. 9" =~ /(?<number>\d+)/ number # => nil (not assigned) /(?<number>\d+)/ =~ "no. 9" number #=> "9"