Learn Ruby – How To Check Whether a String Contains a Substring

The String class in Ruby comes with several built-in search methods of values within a String, but there is none with a straight name as “contains” or “search” that would express the ability to search and find substrings, as the word “Hello” within the string “Hello World.” This type of research exists, of course, but it is hidden within the method “index”.

Ruby – Searching Strings

To search for a substring within a string, just inform the content and the number of characters you want to consider from this index:

Together with the code described above, or better, before using it, you must search what the exact position of “World” inside the String, and then recover it inside the String. Using the index method:

The above code returns “nil”, or null, indicating that the desired word does not exist inside the String. This happens because this search is considering only the written word in lowercase. We should then make this search case insensitive. To do this, we add the “i” at the end of our previous search:

The search returned the index where the first letter of the word is within the String. Using the first code in this article, now we get the word we want.

Ruby – Searching Strings with the scan method

You can also use the method .scan. In this method, a pattern is declared using a regex (regular expression) as the argument that should be searched. The return is an array with the search value:

Do you know other ways how to check whether if a string contains a substring in Ruby? Share your comments in the section below!

If you want to explore other questions about Ruby, you can check our videos section! Below we have some examples:


Get More Benefits With LiveEdu Pro

You can also subscribe to some channels that broadcast in Ruby, such as the following:

how to check whether a string contains a substring programming rubyexcid3

how to check whether a string contains a substring programming rubyzoer

Another cool way to find out interesting things about Ruby is to access our project page!

  • Edgar Burkhart

    Best explanation and clear idea. I understood it in one go. Thanks livecoding

Read previous post:
Learn JavaScript – How to Verify if a Checkbox is Checked in jQuery?

  If you are using jQuery and want to find out if a particular checkbox is checked, inside jQuery there...