D. Sow D. Sow - 2 months ago 10
Ruby Question

Why do class objects have access to instance modules in Kernel module?

I'm learning Ruby and recently discovered something I didn't quite understand. When mixing in modules into Classes, a class Object can not access the modules instance methods.

module Swimmable
def swim
puts 'can swim'
end
end

class Fish
include Swimmable
end

Fish.swim


Result is
undefined method 'swim' for Fish:Class (NoMethodError)
which is expected

However if the instance method is defined in the Kernel module, I can access it using a class object and an instance object.

module Kernel
def swim
puts 'can swim'
end
end

class Fish; end

Fish.swim # => can swim
Fish.new.swim # => can swim


What makes the class object
Fish
able to access instance methods in the Kernel module?

Answer

From the documentation:

The Kernel module is included by class Object, so its methods are available in every Ruby object.

Both Fish instances and the Fish class itself are Objects, so they have all the methods defined in Kernel.

In the first case you get the error because including Swimmable in Fish will make Swimmable members available on instances of Fish, but not on the class itself.