Ruby: Check if string contains substring

August 7, 2022  ‐ 1 min read

To check whether a Ruby string contains a given substring the include? string method seems most convenient. You can pass it the substring as an argument and it returns either true or false.

if 'rubylation'.include?('ruby')
  puts 'We found a match!'

#=> We found a match!

The include? method looks for an exact match of the substring in the string. Therefore it is case sensitive for example.

If you are looking for a more advanced way of looking for a substring in a string you can look at regular expressions.

This returns the index of the match if found, if the string doesn't contain a match for the regular expression nil is returned.

'rubylation' =~ /Ruby/
#=> nil
'rubylation' =~ /Ruby/i
#=> 0