to_s method overrides class: Ruby step by step (b)

#  override to_s method


class Thing
     def set_name(aName)
        @name = aName
    end
    
     def get_name
         return @name
    end
end

class Treasure
     def initialize(aName, aDescription)
      @name = aName
      @description = aDescription
    end
    
     def to_s  #  override default to_s method
         " The #{@name} Treasure is #{@description}\n "
    end
end

thing1 = Thing.new
thing1.set_name( " A lovely Thing ")
puts thing1.get_name
puts thing1.to_s

t1 = Treasure.new( " Sword "" an Elvish weapon forged of gold ")
t2 = Treasure.new( " Ring "" a magic ring of great power ")
puts t1.to_s
puts t2.to_s
#  The inspect method lets you look inside an object
puts  " Inspecting 1st treasure: #{t1.inspect} "

Reproduced in: https: //www.cnblogs.com/davidgu/archive/2012/06/12/2546668.html

Guess you like

Origin blog.csdn.net/weixin_34161029/article/details/93802812