为什么[].all?{|a| a.include?('_')} 返回 true?
为什么
[].all?{|a| a.include?('_')}
返回true
?
Why does
[].all?{|a| a.include?('_')}
return true
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的代码询问以下语句的真实性:“对于空列表中的所有元素
a
,a
包含字符'_'
。 ”因为空列表中没有元素,所以该语句为真。 (这在逻辑上被称为空洞的真理。)如果你改为尝试找到一种方法使该表达式为假。这需要空列表中至少有一个元素,且不包含'_'
。但是,空列表是空的,因此不能存在这样的元素。因此,该陈述不可能是假的,因此它一定是真的。Your code asks about the truth of the following statement: "For all elements
a
in the empty list,a
includes the character'_'
." Because there are no elements in the empty list, the statement is true. (This is referred to as vacuous truth in logic.) It might be easier to understand if you instead try to find a way to make that expression false. This would require having at least one element in the empty list which did not contain'_'
. However, the empty list is empty, so no such element can exist. Therefore, the statement can't meaningfully be false, so it must be true.all?
会将数组的每个元素传递到块{|a| a.include?('_')}
,如果该块不返回false
或nil
,则返回true
任何元素。由于数组没有元素,因此块永远不会返回false
或nil
,因此all?
返回true
。all?
will pass every element of the array to the block{|a| a.include?('_')}
, and returntrue
if the block doesn't returnfalse
ornil
for any of the elements. Since the array has no elements, the block will never returnfalse
ornil
and soall?
returnstrue
.如果块从不返回 false 或 nil,则
all?
返回 true。该块永远不会被调用,因此它永远不会返回 false 或 nil,因此all?
返回 true。all?
returns true if the block never returns false or nil. The block never gets called, therefore it never returns false or nil and thereforeall?
returns true.Even
返回
true
,原因在 bcat 的答案中解释。Even
returns
true
, for the reasons explained in bcat's answer.