How to check whether a string contains a substring in Ruby?
I have a string variable with content as follows:
varMessage =
"hi/thsid/sdfhsjdf/dfjsd/sdjfsdnn"
"/my/name/is/balaji.son"
"call::myFunction(int const&)n"
"void::secondFunction(char const&)n"
.
.
.
"this/is/last/line/liobrary.so"
in above string i have to find a sub string ie
"hi/thsid/sdfhsjdf/dfjsd/sdjfsdnn"
"/my/name/is/balaji.son"
"call::myFunction(int const&)n"
How can I find it? I just need to determine whether the substring is present or not.
You can use the include?
method:
my_string = "abcdefg"
if my_string.include? "cde"
puts "String includes 'cde'"
end
If case is irrelevant, then a case-insensitive regular expression is a good solution:
'aBcDe' =~ /bcd/i # evaluates as true
This will also work for multi-line strings.
See Ruby's Regexp class.
你也可以这样做...
my_string = "Hello world"
if my_string["Hello"]
puts 'It has "Hello"'
else
puts 'No "Hello" found'
end
# => 'It has "Hello"'
链接地址: http://www.djcxy.com/p/60404.html
上一篇: 如何检测文件是否可以在Ruby中写入?