Once you have an array, you can manipulate the elements stored in it, such as creating, reading, updating, and deleting elements.
In this short guide, we will explore various ways to find elements in an array.
1. Include Method
To determine if a value is in an array elements’, you can use the include? method.
values.include? 20
=> true
The include? method returns a Boolean value. True if the array contains the specified element and false if the element is not found.
=> false
2. Using the Select Method
Ruby provides a method called select that allows you to define a specific condition. It then evaluates the elements in the array that match the set condition and returns them in a new array.
values.select {|i| i > 33}
=> [40, 50]
The select method is handy for filtering out elements that only match a specific condition.
It is good to note that the select method does not perform the actions in place. However, it creates a new array with matching elements.
To perform the select operation in place of the original array, you can use the select! method.
3. Using the Index Method
To find the index of an element in the array by specifying its value, you can use the index method.
values.index 40
=> 3
If the specified value is within the array, the method will return its index, which you can use to fetch the item.
4. Using the Find Method
The find method is similar to the select method. However, it returns only the first value that matches the specified condition. Hence, if the array contains duplicate values, it will only return the first match.
values.find {|i| i % 2 == 0}
In the example above, the find method searches the array for the first that matches the specified condition.
In our example, that element is 2. However, four also evaluates to true, but the method does not include it as it’s not the first element.
HINT: Ruby provides a find_all method that works similar to the select method discussed previously.
5. Using the find_index
The find_index method is similar to find. However, it returns the index of the first matching element in the array.
values.find_index {|i| i % 2 == 0}
=> 1
The first matching value is at index 1.
Closing
This guide illustrated various methods and techniques you can use to find an element in an array.
Thank you for reading!