There are several ways to do this, and their outputs differ based on your needs
.include?
– returnstrue
if the element is found,false
if not.index
– returns the index of the first occurrence of the element in the array, ornil
if it isn’t found.find
,.detect
– Interchangeable. Return the first element which matches the criteria in the passed block, ornil
if nothing matches.select
,.filter
,.find_all
– Interchangeable. All return an array containing all elements which match the criteria in the passed block, returns[]
if no matches are found.
Let’s do a couple of examples.
Array.include?
Simple:
numbers = [1, 2, 3, 4]
numbers.include?(2) # true
numbers.include?("hi") # false
Array.index
This method is a bit confusingly named. It gives you the first index at which the given element appears, not the element at the index given.
numbers = [1, 2, 3, 2, 1]
numbers.index(2) # 1
numbers.index(4) # nil
Array.find and Array.detect
Two names for the same method, both return the first matching element:
numbers = [1, 2, 3, 2]
numbers.find { |x| x.even? } # 2 (yes, ruby has built-in .even? and .odd?)
numbers.find { |x| x == "hi" } # nil
numbers.detect { |x| x.even? } # 2
numbers.detect { |x| x == "hi" } # nil
Array.select, Array.filter, Array. find_all
These three all behave identically when operating on arrays11.
numbers = [1, 2, 3, 4, 5]
numbers.select { |x| x.even? } # [2, 4]
numbers.select { |x| x > 10 } # []
numbers.filter { |x| x.even? } # [2, 4]
numbers.filter { |x| x > 10 } # []
numbers.find_all { |x| x.even? } # [2, 4]
numbers.find_all { |x| x > 10 } # []
In most languages, this method is called filter
. Filter was not originally a method in ruby, but it was added in version 2.6.3 in April 2019.
Notes
filter
does not exist on ruby hashes, andfind_all
andselect
have different return types when working with hashes. For more detail, go here. โฉ๏ธ
Helpful Links