Ruby Check if String Contains Substring

In this tutorial, you will find various methods of determining if a given string contains a particular substring. This is a prevalent string manipulation technique that allows you to perform operations such as input sanitation.

Ruby Check if String Contains Substring

Method 1 - Using the include method.

Ruby is a language developed with simplicity and efficiency in mind. Hence, you will find simple tools and methods that allow you to perform standard options within the language quickly.

One such method is the include? method. As the name defines, the method allows you to check whether a given input string contains a defined substring.

The function returns true if the substring is in the source string and false if otherwise.


puts 'Hi, welcome to geekbits'.include?('geekbits')


=> true

If the substring is not found in the source string, the function returns false, as shown in the example below:

irb(main):002:0> 'Hi, welcome to geekbits'.include?('python')


=> false

Method 2 - Using Regular Expressions.

Of course, we cannot forget regex. It is one of the most potent tools for string and pattern matching. Ruby allows us to use Regular Expressions to find a specific pattern (substring) to locate if a substring is contained in a given string.

We can use the =~ operator to check for a matching substring enclosed in // .

The regular expression method should return the index of the matching pattern as shown below:

irb(main):003:0> 'welcome to geekbits' =~ /geekbits/


=> 11

If the specified pattern (substring) is not located in the source string, the method returns nil, as shown:

irb(main):004:0> 'welcome to geekbits' =~ /nopattern/


=> nil


In this post, you learned two methods of determining if a substring is located in a given source string using Ruby built-in methods.

If you enjoy our content, please consider buying us a coffee to support our work:

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.