18

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).

2
  • Can you give what the output should be? Commented Mar 26, 2013 at 16:37
  • I added the output as a comment in the code. ary.some should ouput true in that usecase Commented Mar 26, 2013 at 16:48

2 Answers 2

31

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

["1", "2", "3"].any? { |x| x.to_i == 2 } #=> true
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what i was looking for. I didn't knew of Enumerable ! Thanks alot !
0

If you are really looking for some? you might want something like this

module Enumerable
  def some?
    self.any? && !self.all?
  end
end

This will give you true only if some of the elements are set but not all.

Check out the snippet here https://coderwall.com/p/wcgj2w

1 Comment

[true].some((e) => e) is true. Some does not logically or in JS exclude the possibility of all being true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.