在Ruby中,我如何从派生类中的不同方法调用基类方法,该方法覆盖同一方法?

jucafojl  于 2023-08-04  发布在  Ruby
关注(0)|答案(2)|浏览(104)

如果我有一个方法为'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

字符串

6qftjkof

6qftjkof1#

你可以使用方法#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"
blmhpbnm

blmhpbnm2#

alias_method可以做到:
使new_name成为方法old_name的新副本。这可用于保留对被重写的方法的访问。

  • https:rubyapi.org/3.2/o/module#method-i-alias_method*
class Base
  def a
    puts "hi, this is Base.a"
  end
end

class Derived < Base
  alias_method :base_a, :a

  def a
    puts "hi, this is Derived.a"
  end

  def b
    base_a
  end
end

个字符

相关问题