Omar Khan Omar Khan - 4 months ago 27
Ruby Question

Ruby Kernel#autoload and Module#autoload difference

What is the difference between

Kernel#autoload
and
Module#autoload
? What is the context in which each is used?

Answer

As it might be seen in source code of these methods in standard documentation, Kernel#autoload calls Module#autoload after casting the receiver to it’s class.

When one uses the most common approach and calls autoload on the class level:

class C
  autoload(:M, 'm')
end

the Module#autoload is called because Class < Module. Since the receiver is in this case already a Class’ instance, there is no necessity in explicit cast.

On the other hand, one might need to call autoload within a method body:

class C
  def c
    autoload(:M, 'm')
  end
end

In the latter case the receiver is an instance, and unless it’s a Module descendant, Kernel#autoload is called, which, in turn, retrieves the class of this instance and passes the call to it’s Module#autoload.