メモ

クラスの生成と #to_s のオーバーライド

class Song
  def initialize(name, artist, duration)
    @name = name
    @artist = artist
    @duration = duration
  end

  def to_s
    "Song: #@name--#@artist (#@duration)"
  end
end

song = Song.new("Bicylops", "Fleck", 260)
song.inspect
=> "#<Song:0x297dce8 @artist=\"Fleck\", @name=\"Bicylops\", @duration=260>"
song.to_s
=> "Song: Bicylops--Fleck (260)"

クラスの継承

class KaraokeSong < Song
  def initialize(name, artist, duration, lyrics)
    super(name, artist, duration)
    @lyrics = lyrics
  end
  def to_s
    super + " [#@lyrics]"
  end
end

song = KaraokeSong.new("Bicylops", "Fleck", 260, "And now, the...")
song.to_s
=> "Song: Bicylops--Fleck (260) [And now, the...]"

プログラミングRuby 第2版 言語編

プログラミングRuby 第2版 言語編