How to negate a disjunction
I am a little confused with Enumerator#reject in ruby. Consider the following code:
(1..10).select {|i| i % 3 == 0 || i % 5 == 0 } => [3, 5, 6, 9, 10]
Shouldn't the following line be equivalent?
(1..10).reject {|i| i % 3 != 0 || i % 5 != 0 } => []
If I just use one condition on the reject method, the result is as expected. but If I include the OR operator the res开发者_Python百科ult turns out to be empty. Could somebody clarify this for me.
(1..10).reject {|i| i % 3 != 0} => [3, 6, 9]
You are making a basic logic mistake:
!(A || B)
is equivalent to !A && !B
and NOT equivalent to !A || !B
.
So if you change the ||
in your second example to a &&
, then your second example would give the same result as the first:
(1..10).reject {|i| i % 3 != 0 && i % 5 != 0 } # => [3, 5, 6, 9, 10]
You have run into one of De Morgan's laws.
p And q = Not((Not p) Or (Not q))
p Or q = Not((Not p) And (Not q))
It was close, but you forgot to change the operator.
In the second piece of code, you changed the equality, so you'll need to change the ||
to &&
.
(1..10).reject {|i| i % 3 != 0 && i % 5 != 0 } => [3, 5, 6, 9, 10]
精彩评论