1

我正在尝试在 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
4

2 回答 2

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
于 2011-04-23T06:25:50.920 回答
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
于 2015-12-05T20:44:23.727 回答