如果我有一个带有方法‘a’的基类和一个重新实现方法‘a’的派生类,我只需调用super就可以从Derived.a调用base.A;我如何从不同的派生类方法调用基类‘a’?

class Base
  def a
    puts "hi, this is Base.a"
  end

end

class Derived < Base
  def a
    puts "hi, this is Derived.a"
  end

  def b
    # here is where I want to call Base.a
    Base.a  # this doesn't work
    
  end
end

推荐答案

您可以使用方法Method#super_method:

class Base
  def a
    puts "hi, this is Base.a"
  end
end
class Derived < Base
  def a
    puts "hi, this is Derived.a"
  end

  def b
    # here is where I want to call Base.a
    method(:a).super_method.call
  end
end
Derived.new.b
hi, this is Base.a

更广泛地说,您可以有参数和/或块.

class Base
  def c(x, &block)
    puts "ho, this is Base.c"
    block.call(3*x)
  end  
end
class Derived < Base
  def c(x, &block)
    puts "ho, this is Derived.c"
    block.call(x)
  end  

  def d(x, &block)
    method(:c).super_method.call(x, &block)
  end
end
Derived.new.d(5) { |x| puts "#{x} is a lot" }
ho, this is Base.c
15 is a lot

您还可以执行以下操作.

class A
  def a
    "A.a"
  end
end
class B < A
  def a
    "B.a"
  end
end
class C<B
  def a
    "C.a"
  end
  def test
    method(:a).super_method.super_method.call
  end
end
C.new.test
  #=> "A.a"

Ruby相关问答推荐

如何从外部获取给定 lambda 的参数值,而不显式返回其绑定?

有没有一种简单的方法可以在 Ruby 中获取图像尺寸?

检测安装的 CPU 数量

出于调试目的,如何打印有关 NET:HTTPRequest 的信息?

如何使用 if..else 块的结果分配变量?

Ruby 中是否有像 C 中一样的主要方法?

osx bash上的树命令

Ruby 中 Postgres 查询的简单示例

您如何将 Cucumber 场景标记为待处理

如何将消息附加到 RSpec 判断?

Ruby 的排序方法使用哪种算法?

用反斜杠单引号替换单引号

Ruby Koan 151 引发异常

如何设置方法测试中使用的私有实例变量?

为什么显式返回会对 Proc 产生影响?

何时在 Ruby 中使用 `require`、`load` 或 `autoload`?

Ruby中的urldecode?

相当于 Ruby 的 cURL?

Ruby 类继承:什么是`<<`(双倍小于)?

查找模块中可用的类