Ruby 调用超级类';超类方法?
我怎样才能让孩子忽略父母认为有趣的事情,直接去听祖父母的想法呢 子对象仍然从父对象继承,但它只是不同意几个方法 调用超类的超类的方法 另外,如果我的孩子不同意父母的意见,但同意父母的意见,这是否被认为是糟糕的设计Ruby 调用超级类';超类方法?,ruby,Ruby,我怎样才能让孩子忽略父母认为有趣的事情,直接去听祖父母的想法呢 子对象仍然从父对象继承,但它只是不同意几个方法 调用超类的超类的方法 另外,如果我的孩子不同意父母的意见,但同意父母的意见,这是否被认为是糟糕的设计 class Grandparent def fun #do stuff end end class Parent < Grandparent def fun super #parent does some stuff
class Grandparent
def fun
#do stuff
end
end
class Parent < Grandparent
def fun
super
#parent does some stuff
end
def new_business
#unrelated to my parent
end
end
class Child < Parent
def fun
super
#child also does some stuff
end
def inherit_new_business
new_business
#stuff
end
end
class祖父母
def fun
#做事
结束
结束
班级家长<祖父母
def fun
超级的
#父母做一些事情
结束
def新业务
#与我父母无关
结束
结束
类子<父
def fun
超级的
#孩子也做一些事情
结束
def继承新业务
新业务
#东西
结束
结束
在Ruby中,通过组合而不是继承来获得这种行为通常比较容易。为了实现这一点,包含了包含您希望类具有的特定行为的模块
但如果您必须使用继承,您可以这样做:
class Child < Parent
def fun
GrandParent.instance_method(:fun).bind(self).call
# fun child stuff
end
end
类子类<父类
def fun
GrandParent.instance_方法(:fun).bind(self.call)
#有趣的儿童用品
结束
结束
这正是它所说的。从祖父母类中获取实例方法
fun
,将其附加到当前实例对象self
并调用它。语法错误:(irb):1:类/模块名称必须是常量
是的,我目前正在考虑不同的方法来设计脚本,但效果很好。