Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negate a predicate Proc in Ruby

Tags:

ruby

I have a Proc, which is predicate.

Proc.new { |number| number.even? }

Is there a way to somehow create another Proc which have the opposite meaning? I can't change the "body" of the Proc, because the Proc will come as function parameter. So I want something like this:

not(Proc.new { |number| number.even? }
# which of course doesn't work :(

and I want it to do the same as

Proc.new { |number| number.odd? }

The idea is that I want a function similar to this:

def negate(proc)
  negated proc with meaning opposite of this of proc
end

Thank you very much in advance!

like image 855
Faery Avatar asked Oct 20 '25 01:10

Faery


2 Answers

The following method returns the procedure opposite to the provided one.

def negate(procedure)
  Proc.new { |*args| !procedure.call(*args) }
end

or, using shorter notation:

def negate(procedure)
  proc { |*args| !procedure.call(*args) }
end
like image 94
Marek Lipka Avatar answered Oct 22 '25 03:10

Marek Lipka


Does this help at all?

p = Proc.new { |number| number.even? }
p.call(1) #=> false
!p.call(1) #=> true
like image 36
Bala Avatar answered Oct 22 '25 04:10

Bala