Ruby regex "contains a word"

You can do it with

string =~ /join/i
# /i makes it case insensitive

or

string.match(/join/i)

A little update regarding the performance comment:

>> s = "i want to join your club"
>> n = 500000
=> 500000
>> Benchmark.bm do |x|
..     x.report { n.times { s.include? "join" } }
..   x.report { n.times { s =~ /join/ } }
..   end
       user     system      total        real
   0.190000   0.000000   0.190000 (  0.186184)
   0.130000   0.000000   0.130000 (  0.135985)

While the speed difference really doesn't matter here, the regex version was actually faster.


Correct solution to find an exact WORD in a string is

the_body.match(/\bjoin\b/i) or use other regex:

(\W|^)join(\W|$)

Please note, we need to find whether "join" WORD exists or not in the string. All above solution will fail for strings like: they are joining canals or My friend Bonjoiny is a cool guy

Tags:

Ruby

Regex