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

后端 未结 3 1039
臣服心动
臣服心动 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:19

    This is more a workaround than a solution, suitable if you don't want to define the function on main:

    module Talk
    
      def self.extended(mod)
        mod.module_eval do
          def hello
            puts "hello there"
          end
        end
      end
    
    end
    
    module Kernel
      extend Talk
    end
    

    Incidentally, I wonder why the behaviour is different in this case. Shouldn't module_eval have the same effect as module Talk; end?

提交回复
热议问题