How to check if a value exists in an array in Ruby

Published on 13-01-2022

Ruby has eleven methods to find elements in an array.

The preferred one is include? or, for repeated access, create a Set and then call include? or member?.

Here are all of them:

array.include?(element) # preferred method
array.member?(element)
array.to_set.include?(element)
array.to_set.member?(element)
array.index(element) > 0
array.find_index(element) > 0
array.index { |each| each == element } > 0
array.find_index { |each| each == element } > 0
array.any? { |each| each == element }
array.find { |each| each == element } != nil
array.detect { |each| each == element } != nil

They all return a trueish value if the element is present.

← Previous post Blog index Next post →

Ready to get started? Use Callcounter API analytics to innovate faster