假设我有一个包含三个子类的基类。基类有一个大多数子类通用的方法,它有一个别名:
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 毫升
。
我明白为什么;别名是在父类(super class)级别创建的。我知道这可以通过在发散类中重新定义 alias_method
来解决。但是还有其他方法吗?
显然,使用 to_s
的方法是可行的:
class Beer
def bottle_content
'250 ml'
end
def to_s; bottle_content; end
end
但也许有更优雅的方法?
最佳答案
如果您只需要委托(delegate)行为而无需手动编写新方法,我可能会建议 Forwardable
.
require 'forwardable'
class Beer
extend Forwardable
def bottle_content
'250 ml'
end
def_delegator :self, :bottle_content, :to_s
end
它的真正目的是用于将方法委托(delegate)给其他 对象,但没有什么可以说我们不能这样做,只需将它传递给: self
作为第一个参数。
irb(main):001:0> puts Duvel.new
330 ml
=> nil
关于ruby - 如何让 Ruby 中的 alias_method 使用子类的自定义方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56725597/