从Ruby中的子类方法调用父类中的方法

时间:2013-08-26 16:37:20

标签: ruby

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

我知道PHP和其他语言确实有这个功能,但是在Ruby中找不到一个很好的方法。

在这种情况下会怎么做?

5 个答案:

答案 0 :(得分:78)

如果方法名称相同,即您覆盖方法,则可以使用super。否则,您可以使用alias_method或绑定。

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

答案 1 :(得分:17)

super keyword调用超类中同名的方法:

class Foo
  def foo
    "#{self.class}#foo"
  end
end

class Bar < Foo
  def foo
    "Super says: #{super}"
  end
end

Foo.new.foo # => "Foo#foo"
Bar.new.foo # => "Super says: Bar#foo"

答案 2 :(得分:13)

Ruby中的super关键字实际上调用了父类中的同名方法。 (source

class Foo
  def foo
    # Do something
  end
end

class Bar < Foo
  def foo
    super # Calls foo() method in parent class
  end
end

答案 3 :(得分:8)

其他人已经说好了。还有一点需要注意:

在超级类中调用方法super.foo的语法foo 不支持。相反,它会调用super - 方法,并在返回的结果上尝试调用foo

  class A
    def a
      "A::a"
    end
  end

  class B < A
    def a
      "B::a is calling #{super.a}" # -> undefined method `a` for StringClass 
    end
  end

答案 4 :(得分:3)

class Parent
  def self.parent_method
    "#{self} called parent method"
  end

  def parent_method
    "#{self} called parent method"
  end
end

class Child < Parent

  def parent_method
    # call parent_method as
    Parent.parent_method                # self.parent_method gets invoked
    # call parent_method as
    self.class.superclass.parent_method # self.parent_method gets invoked
    super                               # parent_method gets invoked 
    "#{self} called parent method"      # returns "#<Child:0x00556c435773f8> called parent method"
  end

end

Child.new.parent_method  #This will produce following output
Parent called parent method
Parent called parent method
#<Child:0x00556c435773f8> called parent method
#=> "#<Child:0x00556c435773f8> called parent method"

self.class.superclass == Parent #=> true

Parent.parent_methodself.class.superclass会调用self.parent_method的{​​{1}}(类方法) Parent调用super的{​​{1}}(实例方法)。

相关问题