Home » Ruby programming » Ruby programs

Ruby program to check whether an element exists in an array or not

Checking the existence of an element in an array: Here, we are going to learn how to check whether an element exists in an array or not in Ruby programming language?
Submitted by Hrithik Chandra Prasad, on August 16, 2019

Checking the existence of an element in an array in Ruby

In this scenario, we are trying to find the availability of an element in a pre-constructed array. This process has got various ways but here we are stressing upon two of them. One is, with the help of predefined method and second is, with the help of loop. include? method is specifically used for this purpose but when you want to clear your core concepts, you should opt for the second one where the solution is developing from scratch.

Methods used:

  • .include?: This method is used to check the presence of an element in the particular array by passing the string name under " ".
  • puts: used to print some message on the screen.
  • gets: used to take input from the external sources.

Variables used:

  • arr: It is a string array with size 4.
  • ele: It is a string which Is required to be checked in arr.
  • check: This variable is used to store the value returned by .include? method.
  • flag: It is a Boolean variable. The presence of ele will only be verified when it will true.

Ruby code to check whether an element exists in an array or not

=begin 
Ruby program to check the existence of an element
=end

arr= Array["Haridwar","Dehradun","Graphic_Era","Includehelp"]

puts "Enter the element you want to check"
ele=gets.chomp

check = arr.include? ele   #method 1
if(check==true)
	puts "#{ele} is an element of Array (Checked through .include? method)"
else
	puts "#{ele} is not an element of Array (Checked through .include? method)"
end

flag=false
for i in 0..arr.length   #method 2
	if arr[i].to_s== ele
		flag=true
	end
end

if flag==true
	puts "#{ele} is an element of Array (Checked through loop)"
else
	puts "#{ele} is not an element of Array(Checked through loop)"
end

Output

RUN1:
Enter the element you want to check
Rishikesh
Rishikesh is not an element of Array (Checked through .include? method)
Rishikesh is not an element of Array(Checked through loop)


RUN2:
Enter the element you want to check
Includehelp
Includehelp is an element of Array (Checked through .include? method)
Includehelp is an element of Array (Checked through loop)

Explanation:

You can see in the above code that we have implemented two ways in a single code. The code can be broken down as per the requirement. When we are processing through the loop, we are checking each element of arr with the ele. If it is found, then the Boolean variable will be made true.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.