Replacing the to_s method in Ruby. Not printing out desired string

后端 未结 4 1106
甜味超标
甜味超标 2020-12-11 12:05

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

4条回答
  •  借酒劲吻你
    2020-12-11 12:32

    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.

提交回复
热议问题