
_array_index is faster than _array_member? by 3x ± 0.1 _array_find_index_each is similar to _array_any_each _array_member? is faster than _array_index_each by 2x ± 0.1 _array_index is faster than _array_member? by 2x ± 0.1 _array_find_index is similar to _array_index _array_include? is similar to _array_find_index _array_detect_each is similar to _array_find_each _array_member? is faster than _array_detect_each by 2x ± 1.0

_array_find_index_each is faster than _array_member? by 4x ± 1.0

_array_index_each is similar to _array_find_index_each _array_any_each is similar to _array_index_each _array_find_index is faster than _array_any_each by 2x ± 1.0 _array_index is similar to _array_find_index _array_include? is similar to _array_index Which, when run on my Mac OS laptop, results in: Ruby v.2.7.0 Here are all of them: array.include?(element) # preferred methodĪrray.index The preferred one is include? or, for repeated access, creat a Set and then call include? or member?. Ruby has eleven methods to find elements in an array. Raise "Not allowed" unless ALLOWED_METHODS.include?(what.to_sym)Ī quick test reveals that calling include? on a 10 element Set is about 3.5x faster than calling it on the equivalent Array (if the element is not found).Ī final closing note: be wary when using include? on a Range, there are subtleties, so refer to the doc and compare with cover?.

E.g: require 'set'ĪLLOWED_METHODS = Set[:to_s, :to_i, :upcase, :downcase So if you array is constant, for example, it is a good idea to use a Set instead. O(n)), while that lookup for a hash will be constant time (i.e O(1)). Note that if you have many values in your array, they will all be checked one after the other (i.e. OTOH, there is no in operator or #in? method in Ruby itself, even though it has been proposed before, in particular by Yusuke Endoh a top notch member of ruby-core.Īs pointed out by others, the reverse method include? exists, for all Enumerables including Array, Hash, Set, Range. There is an in? method in ActiveSupport (part of Rails) since v3.1, as pointed out by So within Rails, or if you require 'active_support', you can write: 'Unicorn'.in?() # => false
