Ruby “+;”红宝石色
我是ruby新手,我正在阅读Ruby “+;”红宝石色,ruby,Ruby,我是ruby新手,我正在阅读编程ruby并遵循其示例 这是教授继承和消息的代码: 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
编程ruby
并遵循其示例
这是教授继承和消息的代码:
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:未定义的方法
+@'中,表示“[每次我
已离开…]“:字符串(NoMethodError)
然后我做了一个测试:
name="kk"
puts name +"sfds"
此代码不会引发任何错误
有什么问题吗
顺便说一句,我使用的是ruby 2.0.0p247(2013-06-27)[x64-mingw32]您正在更改
字符串上的方法调用。以前,您有效地做到了这一点:
super.+(字符串)
现在,您正在执行这个super(+string)
。+@
方法不是在字符串上定义的(它是在数字上定义的,只返回一个正数),这就是为什么您会看到这个错误。这是一元加号运算符。第二个示例使用二进制加号运算符,它是两个变量的函数。仅供参考,您不需要代码>作为Ruby中的语句终止符:)
name="kk"
puts name +"sfds"