我是 ruby 新手,我正在阅读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
of更改为 this(注意和KaraokeSong
之间没有空格):+
"[#@lyrics]"
def to_s
super +"[#@lyrics]";
end
我会得到错误:
在
to_s': undefined method
+@' 中表示“[对我来说,每次我离开...]”:String (NoMethodError)
但后来我做了一个测试:
name="kk"
puts name +"sfds"
此代码不会引发任何错误。
有什么问题?
顺便说一句,我正在使用ruby 2.0.0p247 (2013-06-27) [x64-mingw32]