0

如何在下面的代码中从 Up 类中获取 Base 的“hello”方法?

class Base
  def hello
    p 'hello from Base'
  end
end

class Up < Base
  def hello_orig
    # how to call hello from Base class?
  end

  def hello
    p 'hello from Up'
  end
end

u = Up.new
u.hello_orig # should return 'hello from Base' 
4

2 回答 2

4

您也可以使用别名。

class Base
  def hello
    p 'hello from Base'
  end
end

class Up < Base
  alias hello_orig hello

  def hello
    p 'hello from Up'
  end
end

u = Up.new
u.hello_orig # should return 'hello from Base' 
于 2012-11-02T10:50:14.367 回答
1

试试这个,

class Base
  def hello
    p 'hello from Base'
  end

end

class Up < Base
  def hello_orig
    Base.instance_method(:hello).bind(self).call

  end

  def hello
    super() 
    p 'hello from Up'
  end

end

u = Up.new
u.hello_orig # should return 'hello from Base' or
u.hello 
于 2012-11-02T10:46:13.023 回答