Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 316
Vlad Zloteanu Avatar asked Nov 18 '10 10:11

Vlad Zloteanu


People also ask

What is difference between include and extend in Ruby?

In simple words, the difference between include and extend is that 'include' is for adding methods only to an instance of a class and 'extend' is for adding methods to the class but not to its instance.

Why do we declare private methods Ruby?

What is a private method in Ruby? It's a type of method that you can ONLY call from inside the class where it's defined. This allows you to control access to your methods.

What is private and protected in Ruby?

protected methods can be called by any instance of the defining class or its subclasses. private methods can be called only from within the calling object. You cannot access another instance's private methods directly.

How do you access a private method in Ruby?

The only way to have external access to a private method is to call it within a public method. Also, private methods can not be called with an explicit receiver, the receiver is always implicitly self. Think of private methods as internal helper methods.


2 Answers

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.

like image 169
Jörg W Mittag Avatar answered Oct 13 '22 01:10

Jörg W Mittag


To be able to run Foo.include(Bar) at any point would most likely be a source of very nasty bugs.

like image 34
Theo Avatar answered Oct 13 '22 02:10

Theo