rubylanguage-designnull

What is the purpose of NilClass, TrueClass, and FalseClass


NilClass, TrueClass and FalseClass having one instance each, namely nil, true and false, which are constants, what is the purpose of having these classes? Why cannot they be instances of the Object class, and all the relevant methods be simply defined as singleton methods on nil, true and false? A related question is, why are these not defined as constants?


Solution

  • It keeps with the idea that "everything is an object" and "objects are specialized by the classes they are instances of".

    nil, true, and false are all objects (and are thus instantiations of a class with methods). The imposition that they are 1) the sole inhabitants of the respective type and are 2) immutable objects allows for implementation optimizations -- and really, isn't one nil enough?

    A helpful error message without specialization for the values: x.class "just works".

    > > nil.foo
    > => #<NoMethodError: undefined method `foo' for nil:NilClass>
    

    I am glad it said NilClass :-)

    This class-instance approach also makes re-opening NilClass -- for better or worse -- as easy and consistent with how it might be done for other types.

    At least as of Ruby 1.9.2 it is not possible to re-assign true, false or nil (Python 2.x allowed re-assignment of True/False, but does not in Python 3.x). Note that because true/false/nil are not constants they can be optimized into the AST -- or whatever the implementation uses -- as "literal values" without a constant look-up.

    > > VERSION
    > => "1.9.2"
    > > true = false­
    > => #<SyntaxError: Can't change the value of true>
    > > [].each {|tru­e|}
    > => #<SyntaxError: Can't change the value of true>
    

    Happy coding.