Home »
Ruby programming »
Ruby programs
Ruby program to check whether a string contains a substring or not
Checking substring in a string: Here, we are going to learn how to check whether a string contains a substring or not in Ruby programming language?
Submitted by Hrithik Chandra Prasad, on August 11, 2019
Checking substring in a string
Given a string and substring, we have to check whether a string contains a substring or not.
A substring is a sequence of characters within a string or in other words, a substring is a part of the string. Ruby provides you a keyword through which you can check the availability of a substring. That keyword is known by ".include?" which takes the specified substring as the parameter under double quotes like .include? “Hello”.
Methods used:
- puts: The method put string is used to put a message on the screen for the user.
- gets: This method is used to take input from the user.
- .include?: One of the functionalities of this keyword is that it is used to analyze the existence of a substring within a string.
Variables used:
- str1: It is being employed for storing the actual string.
- substr2: It is storing the substring to be checked which is provided by the user.
Ruby code to check whether a string contains a substring or not
=begin
Ruby program to check whether a string
contains substring or not
=end
puts "Enter the string:"
str1=gets.chomp
puts "Enter the substring:"
substr1=gets.chomp
if str1.include? substr1
puts "Substring Found"
else
puts "substring Not Found"
end
Output
Run 1:
Enter the string:
My name is Hrithik
Enter the substring:
saksham
substring Not Found
Run 2:
Enter the string:
You are at Includehelp.com
Enter the substring:
at
Substring Found