Presence of a substring in Ruby

I just watched the ‘Ruby Trick Shots’ video. This video basically shows a bunch of very useful methods, libraries and techniques you might be unaware of. If you’re a Ruby developer I would highly recommend it.

One of the ‘tricks’ I found particularly interesting was checking for a substring. Let’s say we have the following string, and we want to check if it contains the word ‘test’.

s = "this is a test"

The normal way of doing this would be to use a Regular expression.

if s =~ /test/
  puts "Found the substring"
end

I know many developers absolutely love Regular expressions, but I’m not a fan. I find them difficult to maintain and not intuitive at all. (This is perhaps a discussion for another day) In any case, a nice and easy way of testing to see if a substring exists is with the following snippet.

if s["test"]
  puts "Found the substring"
end

Here we are actually calling the [] method on the string class – which will simply return nil if the specified string doesn’t exist. As far as I can tell the only downside here is that we can’t ignore the case of the substring. If we want to do that we’ll have to revert back to the Regular expression.

if s =~ /Test/i
  puts "Found the substring"
end

The [] method will happily accept a Regular expression, but I think it’s probably better to stick with this syntax. Happy coding.