Including/Extending the Kernel doesn't add those methods on main:Object

后端 未结 3 1057
臣服心动
臣服心动 2020-12-31 11:01

I\'m trying to add a method into the Kernel module, but instead of reopening the Kernel and directly defining an instance method, I\'m writing a mo

3条回答
  •  太阳男子
    2020-12-31 11:40

    You want include, not extend.

    include adds the contents of the module as instance methods (like when you open a class or module normally); extend adds them as class methods (so in your example, you could call Kernel.hello, though this isn't what you want).

    You might now be inclined to try this:

    module Talk
      def hello
        puts "hello there"
      end
    end
    
    module Kernel
      include Talk
    end
    

    But this won't work either, because main has already been instantiated, and include simply alters the ancestry of Kernel.

    You could force main to include your module at runtime, like this:

    # (in global scope)
    class << self
      include Talk
    end
    

    This way, you're altering the metaclass of main, not Kernel (which would imply including it on a ton of other object you may not want).

    If you do, you can also just do an include Talk in global scope, but beware that this will pollute integers and other things with your methods.

提交回复
热议问题