Search This Blog

February 14, 2015

How to check whether a string contains a substring in Ruby?

Typically, one would expect (at least I end-up trying this first, almost everytime) a method by name contains? to be available for use. Unfortunately, it isn't present.

You could use include? for all case-sensitive cases, like the examples shown below:

sentence = "How are you?"
sentence.include? "How"  # => true
sentence.include? "how" # => false


For case insensitive searches, try something like below:

sentence =~ /How/i  # => 0
sentence =~ /how/i  # => 0
sentence =~ /What/i  # => nil