Join my Laravel for REST API's course on Udemy 👀

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!'
end

#=> 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