Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Why is Nil in the boolean discussion of ruby?

Why is Nill considered a boolean, or at least represented as a boolean value in the Boolean tutorial for ruby? By definition a booean, for the terms of computer science, is a "data type, having two values (usually denoted true and false), intended to represent the truth values of logic and Boolean algebra"

3 Answers

nil is one of the few other values that can be thought of as false similar to how in other languages 0 and 1 can be thought of false and true (respectively). So it's not a boolean itself but is useful to cover here regardless. In case you were wondering nil is of type NilClass.

  foo = nil
  if foo
    # this will never execute
  end

But isn't a boolean supposed to have its own binary. So would it be nil and exists? It just doesn't seem to follow the way that booleans work, at least to me.

nil is certainly not a boolean, it is it's own special value that is used to represent null values. For example instance variables (e.g. @foo) will by default evaluate to nil if they have not previously been set. You can also specifically set a value to nil as I showed in the previous example. To be more clear and to explicitly check a boolean value you can use .nil? which returns true if the object is nil. This makes the code a little more understandable in some cases as well.

  foo = nil
  if foo.nil?
    # do something
  end

I cross posted this question on stack overflow and the answer I got there was very helpful in explaining it. Thought I would post that here in case other people who think like me might understand it better this way:

"Every expression in Ruby is being evaluated to an object and every object has a boolean value.

Many expressions can have a false value, but the only two objects in Ruby to have a boolean value of false are nil and false. That's why."