I’m reading through the excellent Ruby on Rails Tutorial and have encountered the following code.
if 0
true
else
false
end
The above returns true and illustrates how unlike many languages (C being the obvious example), Ruby treats 0 as true. Rather than dismiss the behavior as idiosyncratic, I assume there is a good reason for this significant departure from convention. Python, for instance, treats 0 as False, just as one would expect.
In short, what is the rationale in designing Ruby to treat 0 as true?
I’m guessing that Matz wanted conceptual simplicity of “truthiness” as such – the only “false” values are
falseandnil. Period.Using just
falsewould be the cleanest but there is understandable need for includingnil. To include the integer zero as a special case might open the mental floodgates of questioning truthiness of other types. What about strings, is""false? And arrays, is[]false? And hashes, is{}false? Ad insanitum (see JavaScript)…