Method 1 - Using the
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')
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')
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/
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/
In this post, you learned two methods of determining if a substring is located in a given source string using Ruby built-in methods.