Ruby

Ruby Check If An Array Contains Values

Arrays are a collection of ordered items. Arrays are crucial in many programming languages because they provide flexibility, performance, and refactored code when used appropriately.

An individual item in the array is an array’s element. Each element is identifiable by an index which is a value that describes the element’s position in the collection.

In Ruby, the index of elements in the array starts at 0 from left to right. Hence, the first element in the array is at an index of 0.

Basic Usage

To create an array in Ruby, we use a pair of square brackets followed by the array’s elements separated by a comma.

[1,2,3,4,5]

You can also assign an array to a variable name.

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

Typically when creating arrays, you have initial values to store. However, you can create an empty array and modify its values later in the program.

The following syntax creates an empty array:

myarray = []

Items in an array can be of any type. For example, the following array contains elements of various object types:

myarray = [1,2,34.44,223.92,"hello", {"key"=>"value"}, [1,2,3]]

To fetch the items in an array, you can use their index positions. For example, to get the first element in the array:

print myarray[0]

You can get the index of the last element in the array using its length.

print myarray[myarray.length-1]

How to Check If A Ruby Array Contains A Value

To check if a value is in the array, you can use the built-in include? method.

myarray = [1,2,34.44,223.92,"hello", {"key"=>"value"}, [1,2,3]]
myarray.include? 34.44
=> true

The include? method returns true if the specified value is in the array and false if not.

myarray.include? 100
=> false

If you have a nested array, you will need to reference the inner array when calling the include.

For example, the following example returns false.

myarray.include? 3
=> false

To specify that you want to check the inner array, use its index as:

myarray[6].include? 3
=> true

The same case applies to a dictionary:

myarray[5].include? "key"
=> true

Closing

This guide has illustrated how to check if an element exists within an array using the include? method.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list