Ruby:如何获取在子类中重新定义的父方法

时间:2012-11-02 10:38:17

标签: ruby-on-rails ruby

如何在下面的代码中从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' 

2 个答案:

答案 0 :(得分: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' 

答案 1 :(得分: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