Table of contents
1.
Introduction
2.
Brief Introduction to Ruby
2.1.
Ruby
3.
array.include?() Method in Ruby
3.1.
Syntax
3.2.
Return Type
3.3.
Time Complexity
4.
Examples of using the array.include?() Method
4.1.
Example 1: Array of Strings
4.2.
Ruby
4.3.
Example 2: Array of Integers
4.4.
Example 3: Array of Objects
4.5.
Ruby
4.6.
Example 4: Hash Map
4.7.
Ruby
4.8.
Example 5: Finding Substrings
4.9.
Ruby
5.
Internal Implementation of the array.include?() Method
5.1.
Ruby
6.
Alternatives of array.include?() in Ruby
6.1.
enumerable.any?() Method
6.2.
Ruby
6.3.
enumerable.find() Method
6.4.
Ruby
6.5.
enumerable.index() Method
6.6.
Ruby
7.
Frequently Asked Questions
7.1.
What is nil in Ruby?
7.2.
What is a dynamically typed language?
7.3.
What is enumerable in Ruby?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Ruby array.include?() Method

Author Abhinav Anand
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Ruby is an object-oriented programming language known for its simplicity due to its clean syntax. It has many built-in methods for manipulating arrays, and include?() is one of them. These methods make it easy for you to perform common operations on arrays without implementing them from scratch.

ruby array.include?() method

In this article, you will learn about the array.include?() method in Ruby.

Let’s get started.

Brief Introduction to Ruby

Ruby is a dynamically typed object-oriented programming language that supports automatic memory management through garbage collection. 

Let’s look at how you can create an array in Ruby.

  • Ruby

Ruby

# creating an array of fruit names

fruits = ["apple", "banana", "orange", "grape", "watermelon"]



# traversing and printing each fruit name

fruits.each do |fruit|

 puts fruit

end
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

output

In this example, the fruits array contains five fruit names, and the each method is used to iterate through each array element. The puts statement is used to print each fruit name to the console.

Arrays in Ruby are dynamic, i.e., you don’t need to specify the size of the array when you create it, and you can also change the size of an array after it’s created by adding or removing elements.

In the next section, we will take a look at the include?() method.

array.include?() Method in Ruby

In Ruby, the array.include?() method checks whether a specific value exists within an array. This method returns true if the given value is present in the array and false if it’s not present.

Syntax

array.include?(value)

 

  • array: This is the name of the array in which you want to perform the search.
     
  • value: This is the target that you want to search for.

Return Type

The array.include?() method returns a boolean value (true or false), indicating whether the specified value is present in the array or not.

Time Complexity

The time complexity of this method depends on the data structure we use it on. This method has a linear time complexity for arrays but O(1) time complexity for a hash set.

Now, let’s take a look at some examples.

Examples of using the array.include?() Method

We will use the array.include?() method on arrays of different data types.

Example 1: Array of Strings

We will first create an array of strings, and then we will use the array.include?() method twice with different value parameters.

  • Ruby

Ruby

vegetables = ["carrot", "broccoli", "spinach", "tomato", "cucumber"] #creating array


puts vegetables.include?("broccoli")

puts vegetables.include?("potato")
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

output

Example 2: Array of Integers

In this example, we will first create an array of integers and use the include?() method twice with different values.


integer_array = [10, 20, 30, 40, 50]

puts integer_array.include?(25)

puts integer_array.include?(30)

Output:

output

Example 3: Array of Objects

In this example, we will first define a custom Product class with name and price attributes.

As the include?() method compares the object identity by default, so we will overload the “==” to ensure it compares the object attributes.

  • Ruby

Ruby

class Product #defining product class

 attr_accessor :name, :price


 def initialize(name, price)

   @name = name

   @price = price

 end


 def ==(other)

   name == other.name && price == other.price

 end

end


#initializing products array

products = [

 Product.new("Printer", 20000),

 Product.new("Mouse", 1500),

 Product.new("GPU", 21000)

]


target = Product.new("GPU", 21000)



if products.include?(target)

 puts "Target found"

else

 puts "Target not found"

end
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

output

Example 4: Hash Map

You can use the include?() method for data structures other than arrays, such as hashmap, set, and string. In this example, we will create a hashmap and use the include?() method to check the presence of a key.

  • Ruby

Ruby

#defining hash map

prices = {

 "printer" => 20000,

 "mouse" => 1500,

 "keyboard" => 3000,

 "GPU" => 25000,

 "headphones" => 3000

}


target = "mouse"



if prices.include?(target)

 puts "Found key in the map"

else

 puts "Key not found"

end
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

output

Example 5: Finding Substrings

As discussed in the previous example, we can use this method on strings. Let’s take a look at an example.

  • Ruby

Ruby

sentence = "Hello, how are you?" #initializing string

if sentence.include?("Hello")

 puts "Substring is present"

else

 puts "Substring is NOT present."

end



if sentence.include?("hello")

 puts "Substring is present"

else

 puts "Substring is NOT present."

end
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

output

In this example, we first created a string, and then we searched for substrings twice. You may have noticed that this method is case-sensitive.

Now, let’s discuss the internal implementation of the array.include?() method in Ruby.

Internal Implementation of the array.include?() Method

The array.include?() method in Ruby uses the linear search algorithm for finding elements in an array. It traverses through the given array and compares each element to the target value until a match is found or it reaches the end. Internally, this method is implemented in C, allowing it to balance ease of development and performance.

Let’s see how you can implement this method directly in Ruby.

  • Ruby

Ruby

#defining custom module

module CustomModule

 def custom_include?(value)

   each do |element|

     return true if element == value

   end

   false

 end

end


#extending the array class

class Array

 include CustomModule

end


numbers = [1, 2, 3, 4, 5] #initialized array



puts numbers.custom_include?(3)

puts numbers.custom_include?(6)
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

output

In this example, we defined a module called CustomModule that contains the custom_include?() method, which traverses the array and checks if any element matches the given value. Then, we extended the built-in Array class with our custom module using the include keyword. It is important to note that the built-in include?() method is optimized, and it also handles searching in different data structures, so it is not recommended to implement it yourself.

In the next section, we will discuss some alternatives of the array.include?() method in Ruby.

Alternatives of array.include?() in Ruby

You can use the following alternatives to check an element's presence in an array or other data structures:-

enumerable.any?() Method

The any?() method checks if an element in the given data structure satisfies the given condition. It returns true if at least one element matches the condition.

  • Ruby

Ruby

numbers = [1, 2, 3, 4, 5]

target = 3

puts numbers.any? { |num| num == target }
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

output

In this example, we first created an array of integers and then used the any?() method with the condition that compares each element with the target.

enumerable.find() Method

The find() method returns the first element in the collection that satisfies a given condition, and if no element satisfies the condition, it returns nil.

  • Ruby

Ruby

numbers = [1, 2, 3, 4, 5]


if numbers.find { |num| num == 3 }

   puts "Target Found" #this only executes if the method returns a non-null value

else

   puts "Target Not Found"

end


if numbers.find { |num| num == 6 }

   puts "Target Found"

else

   puts "Target Not Found"

end
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

output

enumerable.index() Method

The index() method returns the index of the first element that matches the given value, and if no matches the given value, it returns nil.

  • Ruby

Ruby

numbers = [1, 2, 3, 4, 5]


if numbers.index(3)

   puts "Target Found"

else

   puts "Target Not Found"  #this only executes if the method returns a non-null value

end


if numbers.index(6)

   puts "Target Found"

else

   puts "Target Not Found"

end
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

output

Frequently Asked Questions

What is nil in Ruby?

Nil is a special value in Ruby that is used to represent an object's absence or value. It is the Ruby equivalent of nullptr, NULL, or None in other programming languages. Methods like find() and index() return nil if an element is not found in the given container.

What is a dynamically typed language?

A dynamically typed programming language determines the variable types during runtime, so you don’t have to add type names before declaring variables. This makes development easier but can lead to unexpected errors during runtime. Examples of dynamically typed languages are Python, Javascript, and Ruby.

What is enumerable in Ruby?

Enumerable is a module in Ruby that provides you with a collection of methods that help you manipulate and analyze iterable containers such as Sets and Arrays. Some examples of its methods are each(), map(), select(), and reduce().

Conclusion

In this article, you learned about the array.include?() method in Ruby with the help of examples. We also looked at alternatives to this method and an overview of its internal implementation.

You can read the following articles to learn more about Ruby:-

 

Happy Learning!

Live masterclass