下面的程序试图输入一位美国总统和一位法国总统的年龄和姓名。问题是法国总统在点出他的名字、年龄和公民身份(不是我的想法)后说“bein sur”。我对法国总统的口号感到困惑。这是我的代码
class President
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
end
class FrancePresident < President
def self.citizenship
"La France"
end
def initialize(name, age)
super(name, age)
end
def catchphrase
"bien sur"
end
def name
"#{name}, #{catchphrase}"
end
def age
"#{age}, #{catchphrase}"
end
def citizenship
"#{self.class.citizenship}, #{catchphrase}"
end
end
class UnitedStatesPresident < President
def self.citizenship
"The Unites States of America"
end
end
我认为我错误地引用了父类(super class),因为我收到了下面的堆栈错误。
SystemStackError
stack level too deep
exercise.rb:29
我是 Ruby 的新手,所以任何见解都会有所帮助。
最佳答案
您的name
函数生成无限递归,因为它调用自身:
def name
"#{name}, #{catchphrase}" # <-- here, name calls this very function again and again
end
同样适用于 age
。它们应该分别调用实例变量 @name
和 @age
:
def name
"#{@name}, #{catchphrase}"
end
def age
"#{@age}, #{catchphrase}"
end
编辑
使用 super
代替实例变量可能会更好,因为它清楚地表明您正在使用基类的功能并向其添加一些东西(感谢提示,tadman!):
def name
"#{super}, #{catchphrase}"
end
def age
"#{super}, #{catchphrase}"
end
关于Ruby 父类(super class)创建 Stack 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27135370/