2017-10-20 185 views
0

A是父类,BC是它的子类。我可以确保BC都有方法hello通过在类A中添加以下行。Ruby:我希望子类总是声明某些类变量

def hello 
    raise "Implement hello method in sub class" 
end 

我怎样才能acheive一类变量的A每个子类都应该有相同的?

回答

1

据我理解你的问题(不知道你所谓的variable),你可以简单地定义变量是这样的:

def my_variable 
    @my_variable || raise 'Not defined' 
end 

...而不是:

attr_accessor :my_variable # a 'true' instance variable 

希望它可以帮助。