How to Find a Value in a Ruby Array
The best way to find a value in a Ruby array is by using either the find
or detect
method; both are aliases and can be used interchangeably. They accept a block argument and return the first value that satisfies any given condition specified in the block.
The example below looks for the odd number in an array of 2
to 4
.
Example code:
numbers = [2, 3, 4]
odd_number = numbers.find { |n| n.odd? }
puts odd_number
Output:
3
Example code:
numbers = [2, 3, 4]
odd_number = numbers.detect { |n| n.odd? }
puts odd_number
Output:
3
Another way of finding a value in an array is by using the select
method.
Although not efficient but it’s worth mentioning. It’s inefficient because it iterates through the whole array we are searching, regardless of whether the value we are looking for is at the beginning of the array or the end, unlike the find
and detect
that stop iterating soon as they find the value.
It’s also worth mentioning that the select
method is designed to search for multiple values and return them as an array. Assuming we were expecting multiple odd numbers in the example above, the select
would have been a preferred method to use.
Example code:
numbers = [2, 3, 4, 5]
odd_numbers = numbers.select { |n| n.odd? }
puts odd_numbers
Output:
[3, 5]