从 Ruby 中的子类方法调用父类中的方法 [英] Calling method in parent class from subclass methods in Ruby

查看:56
本文介绍了从 Ruby 中的子类方法调用父类中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 super 来初始化父类,但是我看不到任何从子类方法调用父类的方法.

I've used super to initialize parent class but I cannot see any way of calling parent class from subclass methods.

我知道 PHP 和其他语言确实具有此功能,但在 Ruby 中找不到实现此功能的好方法.

I know PHP and other languages do have this feature but cannot find a good way to do this in Ruby.

遇到这种情况怎么办?

推荐答案

如果方法同名,即您要覆盖一个方法,您可以简单地使用 super.否则,您可以使用 alias_method 或绑定.

If the method is the same name, i.e. you're overriding a method you can simply use super. Otherwise you can use an alias_method or a binding.

class Parent
  def method
  end
end

class Child < Parent
  alias_method :parent_method, :method
  def method
    super
  end

  def other_method
    parent_method
    #OR
    Parent.instance_method(:method).bind(self).call
  end
end

这篇关于从 Ruby 中的子类方法调用父类中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆