Ruby中的方法覆盖

dav*_*orb 3 ruby methods overloading

我的代码看起来像这样:

module A
    def b(a)
      a+1
    end
end
class B
   include A
end
Run Code Online (Sandbox Code Playgroud)

我想在B类中编写一个看起来像这样的方法

class B
   def b(a)
      if a==2     # are you sure? same result as the old method
         3
      else
         A.b(a)
      end
   end
end
Run Code Online (Sandbox Code Playgroud)

我如何在Ruby中执行此操作?

con*_*nec 7

您需要该super函数,该函数调用函数的"先前"定义:

module A
  def b(a)
    p 'A.b'
  end
end

class B
  include A

  def b(a)
    if a == 2
      p 'B.b'
    else
      super(a) # Or even just `super`
    end
  end
end

b = B.new
b.b(2) # "B.b"
b.b(5) # "A.b"
Run Code Online (Sandbox Code Playgroud)

  • 你甚至不需要将`(a)`传递给`super`.只有`super`没有任何参数(但没有空括号)将所有参数和任何块传递给超类方法. (2认同)