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
); - Since the right operand might be is an arbitrary object, for
regexp =~ str
there will be called eitherRegexp#=~
orString#=~
.
Note that this does not return a true/false value, it instead returns either the index of the match if found, or nil if not found. Because all integers in ruby are truthy (including 0) and nil is falsy, this works. If you want a boolean value, use #===
as shown in another example.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents