There are several ways to do this, and their outputs differ based on your needs
.include?– returnstrueif the element is found,falseif not.index– returns the index of the first occurrence of the element in the array, ornilif it isn’t found.find,.detect– Interchangeable. Return the first element which matches the criteria in the passed block, ornilif 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") # falseArray.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) # nilArray.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" } # nilArray.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
filterdoes not exist on ruby hashes, andfind_allandselecthave different return types when working with hashes. For more detail, go here. ↩︎
Helpful Links