代码之家  ›  专栏  ›  技术社区  ›  Peter

强制在Ruby中调用kernel::method_name

  •  2
  • Peter  · 技术社区  · 14 年前

    我想添加一个 foo 方法,以便我可以编写 foo(obj) 任何地方,让它做点什么 obj . 有时我想让一个类重写 所以我这样做:

    module Kernel
      private  # important; this is what Ruby does for commands like 'puts', etc.
      def foo x
        if x.respond_to? :foo
          x.foo  # use overwritten method.
        else
          # do something to x.
        end
      end
    end
    

    这很好,很有效。但是,如果我想使用默认值呢 Kernel::foo 在其他覆盖的对象中 ?因为我有一个实例方法 ,我丢失了原始绑定到 内核:Foo .

    class Bar
      def foo  # override behaviour of Kernel::foo for Bar objects.
        foo(3) # calls Bar::foo, not the desired call of Kernel::foo.
        Kernel::foo(3)  # can't call Kernel::foo because it's private.
        # question: how do I call Kernel::foo on 3?
      end
    end
    

    有什么干净的方法可以避开这个吗?我不想有两个不同的名字,我绝对不想 内核:Foo 公众。

    3 回复  |  直到 14 年前
        1
  •  3
  •   Chuck    14 年前

    你可以使用 super 关键字从重写方法调用超类的实现。

    class Bar
      def foo  # override behaviour of Kernel::foo for Bar objects.
        super
        # do something else here
      end
    end
    
        2
  •  3
  •   Community PPrice    7 年前

    一个更普遍的解决方案 super (super不一定总是有效),也请看这条线:

    How to access a shadowed global function in Ruby?

        3
  •  0
  •   x1a4    14 年前

    只使用 alias alias_method 之前 您重新定义kernel.foo以保持对原始版本的引用。