Search code examples
rubymetaprogramminglanguage-designaccess-specifier

On ruby, why include is private and extend is public?


On ruby, what is the reason for include is private, while Object#extend is public?


Solution

  • Object#extend has to be public, otherwise you wouldn't be able to use it. After all, its purpose is to mix in a module into an object, so you'd generally call it like obj.extend(Foo), which isn't possible with private methods.

    Module#include is usually only used inside a module body like so:

    class Bar
      include Foo
    end
    

    I.e. it is usually called without a receiver, so it doesn't have to be public. Of course, it doesn't have to be private either.

    My guess is the reason why it is private is that it is more invasive, because it changes the behavior of every instance of Bar, whereas Object#extend only changes a single object. Therefore, Module#include is in some sense "more dangerous" and thus is made private.

    I don't know whether that is the actual reason, but it is consistent with other similar methods like Module#define_method.