# We can add methods to any class at any point. # This technique is called "mix-ins". # # (We can even add methods to individual objects; see # https://blog.jcoglan.com/2013/05/08/how-ruby-method-dispatch-works/ # about "singleton classes"). class Array; def cdr self[1..-1] end def null? self.size == 0 end end # Examine Array.instance_methods before and after running this code. # --You should see :cdr and :null? added to the method list. #---cut here initially when testing this file--- # Testing in IRB: # load "add-cdr-to-array.rb" # a = [1, 2, 3] # a.cdr.cdr.cdr.cdr.null? # The latter fails! The fourth cdr returns nil, which is of NilClass # (just see nil.class). This class has no null? method defined! # Let's add it: class NilClass; def null? true end end # Now a.cdr.cdr.cdr.cdr.null? succeeds with 'true' # Check nil.class.instance_methods before and after this addition.