Development

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.
Captain Salem 1 min read
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.

Example:

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

Output:

=> 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')

Output:

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

Output:

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

Output:

=> nil

Conclusion

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:

Share
Comments
More from GeekBits

Join us at GeekBits

Join our members and get a currated list of awesome articles each month.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to GeekBits.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.