Ruby - Search for an Element in an Array

1. Introduction

Arrays are used frequently in programming to store collections of data. Often, we need to determine if an array contains a specific value or element. Ruby provides intuitive methods to perform such searches. In this post, we'll demonstrate how to search for an element within a Ruby array.

2. Program Steps

1. Define or initialize an array.

2. Specify the element to be searched for within the array.

3. Use the include? method to check if the array contains the specified element.

4. Print the result to the console.

3. Code Program

# Define an array
numbers = [10, 25, 30, 45, 50, 65]
# Element to be searched for
search_element = 30
# Check if the array contains the specified element
element_found = numbers.include?(search_element)
# Print the result
if element_found
  puts "#{search_element} is present in the array."
  puts "#{search_element} is not present in the array."


30 is present in the array.


1. numbers = [10, 25, 30, 45, 50, 65]: We initialize an array named numbers containing various integers.

2. search_element = 30: We specify the integer 30 as the element we want to search for within the numbers array.

3. numbers.include?(search_element): The include? method is utilized to determine if the numbers array contains the search_element. This method returns a boolean value (true if the element is found, false otherwise).

4. The if statement is used to print the result. If the element_found is true, it confirms that the search_element is present in the array. Otherwise, it indicates that the element is not in the array.

Ruby's built-in include? method simplifies the process of checking for the presence of a specific element in an array.