The `=~` operator
suggest changeif /hay/ =~ 'haystack'
puts "There is hay in the word haystack"
end
Note: The order is significant. Though 'haystack' =~ /hay/ is in most cases an equivalent, side effects might differ:
- Strings captured from named capture groups are assigned to local variables only when
Regexp#=~is called (regexp =~ str); =~calls the method on the left operand.regexp =~ strcallsRegexp#=~.str =~ regexpcallsString#=~.
=~ does not return true or false. It returns the index of the match, or nil if there is no match. Every integer is truthy in Ruby, including 0, and nil is falsy, so the result works in if. For a boolean, use ===, as in another example.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents