ruby的super关键字疑惑

0 views
Skip to first unread message

troy....@gmail.com

unread,
Apr 4, 2007, 9:57:48 AM4/4/07
to artemis-rails
昨天看到书上讲ruby讲到类继承,自然就讲到方法的覆写,也就联系到访问父类的方法,书中的例子如下:

父类:
class Song
# ...
def to_s
"song"
end
def test
"child"
end
end

派生类:
class KaraokeSong < Song
# Format ourselves as a string by appending
# our lyrics to our parent's #to_s value.
def to_s
super + " karao"
end
def test
"parent"
end
end

super在这里代表基类的to_s,在.net里就可以写成base.to_s(),用书上的说法就是调用向上父类的方法本身。但是,如何调用父类的
其他被覆写的方法,比如在上面的KaraokeSong中的to_s调用Song的test方法,我却没有找到答案,谁知道告诉我一声哈
PS:我想到的笨办法是
def KaraokeSong < Song
def test
song = Song.new();
song.test + "parent"
end
end

Reply all
Reply to author
Forward
0 new messages