[英]Negate a predicate Proc in Ruby
我有一個Proc,它是謂詞。
Proc.new { |number| number.even? }
有沒有辦法以某種方式創建另一個具有相反含義的Proc? 我不能改變Proc的“體”,因為Proc將作為函數參數。 所以我想要這樣的東西:
not(Proc.new { |number| number.even? }
# which of course doesn't work :(
而我希望它也能像這樣做
Proc.new { |number| number.odd? }
我的想法是,我想要一個類似於此的函數:
def negate(proc)
negated proc with meaning opposite of this of proc
end
非常感謝你提前!
以下方法返回與提供的過程相反的過程。
def negate(procedure)
Proc.new { |*args| !procedure.call(*args) }
end
或者,使用較短的表示法:
def negate(procedure)
proc { |*args| !procedure.call(*args) }
end
這有幫助嗎?
p = Proc.new { |number| number.even? }
p.call(1) #=> false
!p.call(1) #=> true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.