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
?
string[0] is a new string that contains the first character of string .
Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true. To make life easier, C Programmers typically define the terms "true" and "false" to have values 1 and 0 respectively.
Every object in Ruby has a boolean value, meaning it is considered either true or false in a boolean context. Those considered true in this context are “truthy” and those considered false are “falsey.” In Ruby, only false and nil are “falsey,” everything else is “truthy.”
Because nil and false are not the same objects, and because neither overrides the basic equality operator, the expression false == nil will always be false. Likewise, an Integer like 0 is neither an instance of FalseClass nor NilClass.
I'm guessing that Matz wanted conceptual simplicity of "truthiness" as such - the only "false" values are false
and nil
. Period.
Using just false
would be the cleanest but there is understandable need for including nil
. 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)...
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