Profile image of dvdh8791
Submitted by dvdh8791
over 12 years

Is 0 false in Ruby?

I’ve experimented with some if/else statements:

if 0
    print "a"
elsif 1  
    print "b"
else  
    print "c"
end

This code prints out “a”. Does 0 not false in Ruby?

Answer 506720c46d83060002051f33

7 votes
Best answer

Permalink

No it’s not. :) Zero is a value, and ALL values in Ruby are evaluated to true, EXCEPT for FALSE and NIL.

Profile image of jezreljane
Submitted by jezreljane
over 12 years

2 comments

Profile image of justinraczak
Submitted by justinraczak
over 12 years

I don’t have an explicit frame of reference, but I’m not sure that’s completely accurate. If you run some evaluations, like 0 == true, you’ll get false in return.

Profile image of Edditoria
Submitted by Edditoria
over 12 years

that’s why I like Ruby. I don’t need to deal with such zero-false evil :p

Answer 50669874cd23860002020114

2 votes

Permalink

Nope, as far as i know, it’s not like other languages.
false is false, 0 is an integer, and nil is no value. true is true, 1 is an integer, and nil is no value

Numbers, strings, and all other values evaluate to true. nil evaluates to false. However, nil is not strictly equal to false, because false is a boolean datatype while nil has no datatype.

if false
    print "a"
elsif true  
    print "b"
else  
    print "c"
end

prints out b

edit: added more pointers

Profile image of masfrost
Submitted by masfrost
over 12 years

3 comments

Profile image of fanaugen
Submitted by fanaugen
over 12 years

allow me to correct you on one thing: saying “nil has no datatype” isn’t correct. Technically, nil is an instance of NilClass, and thus is just another Ruby object. So it kind of has a type – the NilClass type.

Profile image of masfrost
Submitted by masfrost
over 12 years

Oh yeah, thanks!

Profile image of Edditoria
Submitted by Edditoria
over 12 years

Alex reminds me the day 1 in Ruby: “Everything is object. 1 is object. Class is object. Nil is object. Object is object. Object is class. Class is class” (then close the book and think I become crazy)