{

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
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Difference between put and println in Ruby with examples

How to check if element exists in hash or not in Ruby with examples

How to check if an element exists in Array or not in Ruby with examples

How to check if the variable is defined in Ruby with examples

How to check the type of a variable is Ruby| Ruby on Rails By Example

How to convert Class or Hash Object to JSON Object Ruby| Ruby on Rails By Example

How to Convert current Unix timestamp epoch to DateTime in Ruby Programming| Ruby on Rails by Example