ruby 代码中的 super 方法做了什么?

What does the method super do in the ruby code?

我想我知道 super 打算覆盖从父 class 继承的相同方法。但是,在下面的消息传递代码示例中,我不知道 super 应该在那里做什么:

class WellBehavedFooCatcher
    def respond_to?(method_name)
      if method_name.to_s[0,3] == "foo"
        true
      else
        super(method_name)
      end
    end
end

那么上面的代码super做了什么?

在此先感谢您!

super 如何使用参数:

  • super - 转发所有参数。
  • super() - 没有转发参数。
  • super(arg1,arg2) - 仅转发 arg1arg2

使用参数调用(在本例中为 method_name),super 仅将此参数发送到它通过方法查找路径找到的下一个 respond_to? 方法。在这种情况下,由于 super 具有唯一的参数,因此 supersuper(method_name) 的行为相同。

下一个 respond_to? 方法很可能是位于 Kernel 模块中的原始 respond_to? 方法,该模块包含在 Object class .

Kernel.methods.include?(:include?) #=> true

I think I know super intends to override the same method inherited from the parent class.

其实恰恰相反。当您覆盖子 class 中的某些方法时,super 用于引用父 class 中相同方法的行为(即原始行为)。

在给定的代码中,缩进是为了使其能够动态响应以foo开头的任何方法,而不改变其他方法的响应能力。第一部分完成者:

if method_name.to_s[0,3] == "foo"
  true

但如果仅此而已,所有其他未定义的方法将只是 return nil,即使它们是在某些父 class 中定义的。如果某些家长 class 对这种方法做出回应,那么 returning nil 响应能力将错误地阻止这种方法。其他部分:

else
  super(method_name)

到 return 这种情况下的正确值。这意味着在其他情况下,执行父级 class 所做的事情。