Ruby's Mix-in chaining not working properly

I'm using Ruby 1.9.3 on Windows. So I want to add methods to be availble in console via Kernel class. Start console.

module Foo
  def bar
    puts "Method is in scope!!!"
  end
end

After add this to Kernel (which is part of Object class)

irb(main):008:0> Kernel.send(:include, Foo)
=> Kernel
irb(main):009:0> bar
"NameError: undefined local variable or method `bar' for main:Object"
# did not work, we need to re-include Kernel in Object class
irb(main):010:0> Object.send(:include, Kernel)
=> Object
irb(main):011:0> bar
Method is in scope!!!
=> nil
irb(main):012:0>

This should have worked only with Kernel.send(:include, Foo) or am I wrong? Am I missing something?

Answers


Yes, in this case you should extend Object directly. But if you're so inclined, you can extend Kernel, just don't forget to re-include it to Object again.

module Foo
  def bar
    puts "Method is in scope!!!"
  end
end

Kernel.send :include, Foo
# bar at this point will generate error

Object.send :include, Kernel
bar
# >> Method is in scope!!!

Also, see this answer for a much more thorough explanation.


Need Your Help