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”.
To search for a substring within a string, just inform the content and the number of characters you want to consider from this index:
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:
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:
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.
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:
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!
We’re thrilled to announce an exciting opportunity for you to win not one but two…
Acquiring practical skills is crucial for career advancement and personal growth. Education Ecosystem stands out…
Artificial Intelligence (AI) has been making significant strides in various industries, and the software development…
Another week to bring you the top yield platforms for three of the most prominent…
If you hold a large volume of LEDU tokens above 1 million units and wish…
It’s another week and like always we have to explore the top yield platforms for…
View Comments
Best explanation and clear idea. I understood it in one go. Thanks livecoding