zoukankan      html  css  js  c++  java
  • Ruby循序渐进(二): 重写类的to_s方法

    # 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}"
    技术改变世界
  • 相关阅读:
    noip2015运输计划
    bzoj3595 方伯伯的oj
    noip模拟赛 #3
    圆方树
    AtCoder AGC #4 Virtual Participation
    noip模拟赛 #2
    AtCoder AGC #3 Virtual Participation
    UNR #1 火车管理
    noip模拟赛
    AtCoder AGC #2 Virtual Participation
  • 原文地址:https://www.cnblogs.com/davidgu/p/2546668.html
Copyright © 2011-2022 走看看