Search code examples
ruby-on-railsrubyarrays

Equivalent to Array.some in ruby/rails


I would like to do the equivalent of Array.some in rails.

Here's an example applied to my usecase which is kind of a more complex include? (i want to apply this to *args):

ary = [:a, :b, :c, d: :x, e: :y] # => [:a, :b, :c, { :d => :x, :e => :y }]
search = :e
contained = ary.some { |x|
  x == search || x.try(:key?, search)
} # => true
assert contained, "We should have found #{search}"

I could do this with ary.map but that would mean go through the whole array and then again test it's contents. I could also use ary.drop_while and verify if it returns an empty array or not but again, i would need to test the result. I've also seen ary.bsearch but there are some strange limitations i don't quite understand about the order of elements.

Have i missed something ? Isn't there an easy way to do that ? i'm using ruby2 and rails 4 (edge).


Solution

  • Javascript Array.prototype.some is equivalent to Ruby Enumerable#any?.

    ["1", "2", "3"].any? { |x| x.to_i == 2 } #=> true