How to check whether a string contains a substring in Ruby

BSalunke picture BSalunke · Nov 24, 2011 · Viewed 790.8k times · Source

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

Adam Lear picture Adam Lear · Nov 24, 2011

You can use the include? method:

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