So, I am just beginning to learn Ruby and I included a to_s method in my Class so that I can simply pass the Object to a puts method and have it return more than just the Ob
Experiential Rule: If the result of to_s is not a String, then ruby returns the default.
Application of Rule: puts() returns nil, which means your to_s method returns nil, and nil is not a String, so ruby returns the default.
Another example:
class Object
def inspect
'obj-inspect'
end
def to_s
'obj-to_s'
end
end
class Dog
def inspect
'dog-inspect'
end
def to_s
nil
end
end
puts Dog.new
--output:--
#
Once to_s fails to return a String, ruby does not continue along the method lookup path to call another to_s method. That makes some sense: the method was found, so there is no need to look up the method in a parent class. Nor does ruby alternatively call inspect() to get a result.
Where does the default come from? I think ruby must directly call the Object#to_s method which is a method written in C--thereby bypassing ruby's method overriding mechanism.