We can use the Ruby include? method to see if an item is contained in a given array. This is pretty straightforward. Here is the code below.
some_array.include?("item")
The include? method will return either true or false based on whether the item is found in the array.
Let’s see a simple example of this below.
Here we will have a simple array of numbers, and just use the include? method to see if a number exists in the array.
nums_array = [1,2,3,4,5]
puts nums_array.include?(2)
puts nums_array.include?(6)
#Output
true
false
Let’s take a look at a couple more examples below.
Using the Ruby include? Method on Hashes and Arrays
In this first example, we will have an array of random object types. We will simply use the include? method to check what it returns when searching for various items in the array.
random_array = ["This","false",true,4,"5"]
puts random_array.include?("This")
puts random_array.include?("this")
puts random_array.include?(false)
puts random_array.include?(true)
puts random_array.include?(5)
#Output
true
false
false
true
false
And let’s take a look at using the include? method on a hash in Ruby.
random_hash = {"first_name" => "Tom", "last_name" => "Smith", "age" => 5}
puts random_hash.include?("last_name")
puts random_hash.include?("Tom")
puts random_hash.include?("id")
#Output
true
false
false
Notice that with Hashes, the include? method will just check the key values and not the values of the key-value pairs.
Hopefully this article has been useful for you to learn how the Ruby include? method works.