Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a string contains a substring in Ruby

Tags:

string

ruby

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.

like image 445
BSalunke Avatar asked Nov 24 '11 14:11

BSalunke


People also ask

How do you check if a string contains a substring?

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.

How do you find the part of a string in Ruby?

A substring is a smaller part of a string, it's useful if you only want that specific part, like the beginning, middle, or end. How do you get a substring in Ruby? One way is to use a starting index & a number of characters, inside square brackets, separated by commas.

How do I use GSUB in Ruby?

gsub! is a String class method in Ruby which is used to return a copy of the given string with all occurrences of pattern substituted for the second argument. If no substitutions were performed, then it will return nil. If no block and no replacement is given, an enumerator is returned instead.


1 Answers

You can use the include? method:

my_string = "abcdefg" if my_string.include? "cde"    puts "String includes 'cde'" end 
like image 87
Adam Lear Avatar answered Oct 26 '22 09:10

Adam Lear