Do you think IIT Guwahati certified course can help you in your career?
No
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.
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.
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.
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
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
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
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
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:-