a, b, c = 0, 1, 2
[a, b, c].find(&:zero?) # => 0
有没有一种方法可以找到第一个使块返回false的元素?
[a, b, c].the_method(&:zero?) # => 1
换句话说,它会像下面这样表现:
[a, b, c].reject(&:zero?).first
a, b, c = 0, 1, 2
[a, b, c].find(&:zero?) # => 0
[a, b, c].the_method(&:zero?) # => 1
[a, b, c].reject(&:zero?).first
目前没有,但您可以通过相对简单的方式创建一个:
a = [0,2,1,0,3]
module Enumerable
def first_not(&block)
find{ |x| !block[x] }
end
end
p a.first_not(&:zero?)
#=> 2
...或者可怕但有趣的hack方法:
class Proc
def !
proc{ |o,*a| !self[o,*a] }
end
end
p a.find(&!(:zero?.to_proc))
#=> 2
...或者简洁但极其危险的方式:
class Symbol
def !
proc{ |o,*a| !o.send(self,*a) }
end
end
p a.find(&!:zero?)
#=> 2
但我建议直接跳过棘手的Symbol#to_proc
用法,说出你想要的:
p a.find{ |i| !i.zero? }
#=> 2
lazy.reject(&:zero?).first
以避免完全遍历数组的性能损失。module Enumerable
def first_reject(&block)
find {|a| not (block.call(a)) }
end
end
reject(...).first
看起来就是你想要的,这有什么问题吗? - Joseph Weissman[a, b, c].find{|i| i != 0 }
- konusfind
的美妙之处在于它在找到第一个匹配值时就停止迭代。 - Phrogz[1,2,3].find(&:nonzero?) # => 1
:-) - Marc-André Lafortune