This forum is now read-only. Please use our new forums at discuss.codecademy.com.

1411 points
Picture
Submitted by
David Hou
over 7 years ago

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?


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.

1064 points
Picture
Submitted by
Jezrel Jane
over 7 years ago

2 Comments

Picture Justin M Raczak over 7 years ago

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.

4fe484ae4f5751000301c642 579207406 Edditoria 愛迪 over 7 years ago

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


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

676 points
50351e0410e6d50002019657 560541457
Submitted by
masfrost
over 7 years ago

3 Comments

Picture Alex J over 7 years ago

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.

50351e0410e6d50002019657 560541457 masfrost over 7 years ago

Oh yeah, thanks!

4fe484ae4f5751000301c642 579207406 Edditoria 愛迪 over 7 years ago

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)