【发布时间】:2019-11-05 14:42:33
【问题描述】:
假设我有一个包含三个子类的基类。基类有一个大多数子类共有的方法,并且它有一个别名:
class Beer
def bottle_content
'250 ml'
end
alias_method :to_s, :bottle_content
end
class Heineken < Beer
end
class Stella < Beer
end
class Duvel < Beer
def bottle_content
'330 ml'
end
end
现在,如果在Duvel 的发散子类实例上调用to_s 方法,则返回250 ml 而不是330 ml。
我明白为什么了;别名是在超类的级别上创建的。我知道这可以通过在分歧类中重新定义alias_method 来解决。但是还有其他方法吗?
显然,使用to_s 的方法会起作用:
class Beer
def bottle_content
'250 ml'
end
def to_s; bottle_content; end
end
但也许还有更优雅的方法?
【问题讨论】:
标签: ruby class inheritance