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?
NilClass , TrueClass and FalseClass having one instance each, namely nil , true and
Share
It keeps with the idea that “everything is an object” and “objects are specialized by the classes they are instances of”.
nil,true, andfalseare 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 onenilenough?A helpful error message without specialization for the values:
x.class“just works”.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,falseornil(Python 2.x allowed re-assignment of True/False, but does not in Python 3.x). Note that becausetrue/false/nilare not constants they can be optimized into the AST — or whatever the implementation uses — as “literal values” without a constant look-up.Happy coding.