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:
1 2 3 |
str = "Hello World" str [5,5] # "World" |
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:
1 2 |
str.index (/ world /) #nil |
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:
1 2 |
str.index (/ world / i) # 5 |
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:
1 2 3 |
a = "Hello World " a.scan (/ w+/) # => [ "Hello", "World"] a.scan (.../) # => [ "Hel", "lo ", "Wor", "ld "] |
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:
You can also subscribe to some channels that broadcast in Ruby, such as the following:
Another cool way to find out interesting things about Ruby is to access our project page!