Jin Hoon Jeffrey Bang Jin Hoon Jeffrey Bang - 1 year ago 78
Ruby Question

Ruby: negate hash passed to proc?

In ruby, the following expression:

x.filter {|n| n.even?}

can also be written as:

so, I am wondering how I would write this expression?
x.filter {|n| !n.even?}

without using

Answer Source

As Sam and engineerskmnky said in the comments below question, it is not possible to perform x.filter { |n| !n.even? } operation directly (and in fact two operations inside the block).

I guess that this was only a trivial example and not a real code so if you have method that does not have the inverse one and you don't want to create one, you can create a lambda or proc in the following way:

not_even = -> (n) { !n.even? }

and then call it on filter as:


You can also use reject method which should give you the same result without the magic of using lambda.