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

How to check whether a string contains a substring in Ruby


You can use the include? method:

my_string = "abcdefg"if my_string.include? "cde"   puts "String includes 'cde'"end


If case is irrelevant, then a case-insensitive regular expression is a good solution:

'aBcDe' =~ /bcd/i  # evaluates as true

This will also work for multi-line strings.

See Ruby's Regexp class for more information.


You can also do this...

my_string = "Hello world"if my_string["Hello"]  puts 'It has "Hello"'else  puts 'No "Hello" found'end# => 'It has "Hello"'

This example uses Ruby's String #[] method.