ruby - 如何让 Ruby 中的 alias_method 使用子类的自定义方法?

标签 ruby class inheritance

假设我有一个包含三个子类的基类。基类有一个大多数子类通用的方法,它有一个别名:

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/

相关文章:

c++ - 嵌套类在继承类中的可见性

C++:从类的公共(public)部分调用类中的私有(private)函数

Ruby 异常处理

ruby-on-rails - 如何编写以关键字结尾的方法

ruby-on-rails - Rails 模块自动加载保持状态

java - “找不到或加载主类”是什么意思?

javascript - 从对象内部的函数获取作用域外的变量 - Javascript

inheritance - JPA 多重鉴别器值

java - 在另一个类中使用来自扩展类的局部变量字符串

ruby : Difference between Instance and Local Variables in Ruby