私はルビーが初めてで、Progamming Ruby
その例を読んでフォローしています。
これは、次のことを教えるコードですInheritance and Messages
。
class Song
def initialize(name, artist, duration)
@name=name;
@artist=artist;
@duration=duration;
end
def to_s
"Song:#@name \t#@artist\t#@duration"
end
end
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("There for me", "Sarah", 2320, "There for me, every time I've been away...")
puts song.to_s
このコードは正常に動作します。
ただし、to_s
のをこれに変更すると(とのKaraokeSong
間にスペースがないことに注意してください):+
"[#@lyrics]"
def to_s
super +"[#@lyrics]";
end
エラーが発生します:
in
to_s': undefined method
+@' for "[There for me, every time I've been away...]":String (NoMethodError)
しかし、私はテストを行います:
name="kk"
puts name +"sfds"
このコードはエラーをスローしません。
どうしたの?
ところで、私は使用していますruby 2.0.0p247 (2013-06-27) [x64-mingw32]