Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does [].all?{|a| a.include?('_')} return true?

Why does

[].all?{|a| a.include?('_')} 

return true?

like image 944
psjscs Avatar asked Nov 02 '10 05:11

psjscs


4 Answers

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.

like image 65
bcat Avatar answered Nov 05 '22 09:11

bcat


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.

like image 40
Nabb Avatar answered Nov 05 '22 09:11

Nabb


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.

like image 2
Reese Moore Avatar answered Nov 05 '22 08:11

Reese Moore


Even

[].all?{ false }

returns true, for the reasons explained in bcat's answer.

like image 1
Andrew Grimm Avatar answered Nov 05 '22 08:11

Andrew Grimm