Why does
[].all?{|a| a.include?('_')}
return true
?
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?
will pass every element of the array to the block {|a| a.include?('_')}
, and return true
if the block doesn't return false
or nil
for any of the elements. Since the array has no elements, the block will never return false
or nil
and so all?
returns 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 therefore all?
returns true.
Even
[].all?{ false }
returns true
, for the reasons explained in bcat's answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With