arrays - Is there a method in Ruby that does the opposite of find? -


a, b, c = 0, 1, 2 [a, b, c].find(&:zero?) # => 0 

is there method finds first element block returns false?

[a, b, c].the_method(&:zero?) # => 1 

in other words, behave same way as:

[a, b, c].reject(&:zero?).first 

there is not, create 1 either clean-ish way:

a = [0,2,1,0,3]  module enumerable   def first_not(&block)     find{ |x| !block[x] }   end end  p a.first_not(&:zero?) #=> 2 

...or horribly-amusing hack way:

class proc   def !     proc{ |o,*a| !self[o,*a] }   end end  p a.find(&!(:zero?.to_proc)) #=> 2 

...or terse-but-terribly-dangerous way:

class symbol   def !     proc{ |o,*a| !o.send(self,*a) }   end end  p a.find(&!:zero?) #=> 2 

but i'd advocate skipping tricky symbol#to_proc usage , saying want:

p a.find{ |i| !i.zero? } #=> 2 

Comments