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
No it’s not. :) Zero is a value, and ALL values in Ruby are evaluated to true, EXCEPT for FALSE and NIL.
2 comments
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.
that’s why I like Ruby. I don’t need to deal with such zero-false evil :p
Answer 50669874cd23860002020114
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
3 comments
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.
Oh yeah, thanks!
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)
Popular free courses
- Free course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner Friendly4 Lessons - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly11 Lessons - Free course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner Friendly6 Lessons