Ruby’s include? and has_value? Methods

Daniel Pericich
2 min readMay 18, 2021

--

Photo by Benjamin Dada on Unsplash

In Ruby, both the Array and Hash classes gain similar methods from the Enumerable module. Enumeration is the act of traversing an object and the Enumerable module extends the methods most common with dealing with arrays and hashes.

Both the map method, which traverses an array or hash and performs an operation on each item before returning a new array, and select method, which returns an array of values that evaluate to true if a given condition is met, are part of the extended functionality of the Enumerable module. Where this module falls short is allowing developers to be able to determine if a given value is part of a collection.

To be able to do this we will have to reach for the include? and has_value? methods. While the methods extended by the Enumerable method work on both arrays and hashes, these methods are part of the Array and Hash classes respectively. Though this is a slight inconvenience, it is still better than some languages that don’t support a built in hash method for this functionality (JavaScript).

Let’s look at some examples to better understand how to use these two methods.

What is Ruby’s include? method?

Include? Should be familiar to anyone coming from a JavaScript background. This array method checks whether the argument passed to it is contained in a given array. This can be great if you want to check if a type of customization is available for a certain product:

Using include? to search array for shirt color options

What is Ruby’s has_value? method?

has_value? is a method that is more unique to Ruby. Similarly to include?, has_value? Is used to check if a collection has a certain value, this time inspecting the key values in a hash. Though there are better methods to use to query for record ids, especially if you are using Ruby on Rails, has_value? can be a good choice if you are searching for a specific key’s value:

Using has_value? to check if user id is contained in hash

Now that you know a little bit more about these methods, let me know how you use has_value? Or include? In the comments below!

--

--

Daniel Pericich
Daniel Pericich

Written by Daniel Pericich

Former Big Beer Engineer turned Full Stack Software Engineer

No responses yet