ruby - Ruby 中的方法覆盖

标签 ruby methods overloading

我有这样的代码:

module A
    def b(a)
      a+1
    end
end
class B
   include A
end

我想在 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

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

最佳答案

您需要 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"

关于ruby - Ruby 中的方法覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7829157/

相关文章:

c# - 如何使用方法实现基类并强制派生类覆盖它?

Java-无法为正方形设置动画,以旋转正方形的形式出现

c++ - 为什么在 C++ 中将函数/方法重载称为静态多态性?

c++ - 将 "enum: int64_t"值写入 std::ostringstream 会将其截断为 int

ruby-on-rails - 为什么我在 Rails 模型回调中收到此 "undefined method"错误,将方法作为符号传递?

ruby - 如果数组在每次迭代期间更新,array.each 能否正常工作?

ruby-on-rails - self.send(method, =, value) 不起作用

ruby - 在使用 ruby​​ 中的 "mail"gem 阅读电子邮件时需要帮助

vb.net - 不要将文字作为本地化参数传递

c++ - 重载运算符 '+='