Ruby Language Regular Expressions and Regex Based Operations =~ operator

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

if /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 either Regexp#=~ or String#=~.

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.



Got any Ruby Language Question?