How to check whether a string contains a substring in Ruby

ghz 1years ago ⋅ 1498 views

Question

I have a string variable with content:

varMessage =   
            "hi/thsid/sdfhsjdf/dfjsd/sdjfsdn\n"


            "/my/name/is/balaji.so\n"
            "call::myFunction(int const&)\n"
            "void::secondFunction(char const&)\n"
             .
             .
             .
            "this/is/last/line/liobrary.so"

In the string I have to find a sub-string:

"hi/thsid/sdfhsjdf/dfjsd/sdjfsdn\n"

"/my/name/is/balaji.so\n"
"call::myFunction(int const&)\n"

How can I find it? I need to determine whether the sub-string is present or not.


Answer

You can use the [include?](https://ruby- doc.org/core-1.9.3/String.html#method-i-include-3F) method:

my_string = "abcdefg"
if my_string.include? "cde"
   puts "String includes 'cde'"
end