在Ruby中调用超级方法

时间:2011-04-23 06:18:50

标签: ruby inheritance methods super derived

我试图在Ruby中定义一些具有继承层次结构的类,但我想在派生类的基类中使用其中一个方法。扭曲的是,我不想调用我所处的确切方法,我想要调用另一种方法。以下不起作用,但这是我想要做的(基本上)。

class A
    def foo
        puts 'A::foo'
    end
end

class B < A
    def foo
        puts 'B::foo'
    end
    def bar
        super.foo
    end
end

2 个答案:

答案 0 :(得分:5)

可能这就是你想要的?

class A
  def foo
    puts 'A::foo'
  end
end

class B < A
  alias bar :foo
  def foo
    puts 'B::foo'
  end
end

B.new.foo # => B::foo
B.new.bar # => A::foo

答案 1 :(得分:0)

更通用的解决方案。

class A
  def foo
    puts "A::foo"
  end
end

class B < A
  def foo
    puts "B::foo"
  end
  def bar
    # slightly oddly ancestors includes the class itself
    puts self.class.ancestors[1].instance_method(:foo).bind(self).call
  end
end

B.new.foo # => B::foo
B.new.bar # => A::foo