view raw
D. Sow D. Sow - 7 months ago 36
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'

class Fish
include Swimmable


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'

class Fish; end

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

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


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.