How to check a string contains a substring in Ruby with examples
This tutorial explains about how to convert a String into upper case or lower case
How to Check a String contains a substring in Ruby?
There are multiple ways we can check a Substring contains in a String Ruby
- use includes method
ruby provides String include? method that checks given string exists in a string or not. This checks for exact case and returns boolean value.
For example.
”abc def”.include? “def” returns true value.
”abc def”.include? “Def” returns false value.
It is case sensitive checking of a string.
Here is an example
name = "Eric John"
if name.include? "John"
puts "Substring exists"
else
puts "Substring does not exists"
end
Output:
Substring exists
- use String match? method
match?
checks for a regular expression pattern or a string, returns true or false.
str.match? pattern/string optional index
Optional Index is an parameter that checks matching of a string from a given index.
puts "John Harry".match? "Harry" #=> true
puts "John Harry".match? "harry" #=> false
puts "John Harry".match? "arry" #=>true
Output:
true
false
true
Here is an example using index
puts "John Harry".match? "Harry",0
puts "John Harry".match? "Harry",5
puts "John Harry".match? "Harry",6
Output:
true
true
false