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.
You can also assign an array to a variable name.
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:
Items in an array can be of any type. For example, the following array contains elements of various object types:
To fetch the items in an array, you can use their index positions. For example, to get the first element in the array:
You can get the index of the last element in the array using its length.
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.include? 34.44
=> true
The include? method returns true if the specified value is in the array and false if not.
=> 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.
=> false
To specify that you want to check the inner array, use its index as:
=> true
The same case applies to a dictionary:
=> true
Closing
This guide has illustrated how to check if an element exists within an array using the include? method.