如何否定析取
我对 Enumerator#reject 在红宝石中。考虑以下代码:
(1..10).select {|i| i % 3 == 0 || i % 5 == 0 } => [3, 5, 6, 9, 10]
以下行不应该是等效的吗?
(1..10).reject {|i| i % 3 != 0 || i % 5 != 0 } => []
如果我只在拒绝方法上使用一个条件,结果将符合预期。但如果我包含 OR 运算符,结果将为空。有人可以帮我澄清一下吗?
(1..10).reject {|i| i % 3 != 0} => [3, 6, 9]
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 result turns out to be empty. Could somebody clarify this for me.
(1..10).reject {|i| i % 3 != 0} => [3, 6, 9]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您犯了一个基本的逻辑错误:
!(A || B)
相当于!A && !B
且不等于!A || !B
。因此,如果您将第二个示例中的
||
更改为&&
,那么第二个示例将给出与第一个示例相同的结果: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:您遇到了德摩根定律之一。
p 和 q = Not((不是 p) 或 (不是 q))
p 或者 q = Not((Not p) And (Not q))
很接近,但您忘记更改运算符。
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&&
.