Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Treat 0 as True in Ruby?

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?

like image 782
enocom Avatar asked Apr 30 '12 16:04

enocom


People also ask

What does 0 mean in Ruby?

string[0] is a new string that contains the first character of string .

Is 0 True or false?

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.

Is nil true in Ruby?

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.”

Is nil false?

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.


1 Answers

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)...

like image 52
maerics Avatar answered Oct 02 '22 13:10

maerics