您可以使用方法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"