Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are modules == mixins in ruby?

Tags:

ruby

I have read in many textbooks that

In Ruby,a class can only be a subclass of one class. Mixins, however, allow classes without a common ancestor to share methods.

In practice, whenever I need to implement multiple inheritance. I have use Modules & not mixins. for example:

Module name_goes_here
  def method_name_goes_here
    .....
  end
end

Then, I just include them in a class

class MySubClass < MySuperClass
  include module_name
end

now, I have referred to multiple ruby books each talking about mixins & then suddenly, all of they start talking about modules without making it clear what is the relation of mixins & modules.

so, Question is: Are modules == mixins in ruby? if yes, then why. if no, then what's the difference?

PS: sorry, if its a silly question

like image 796
CuriousMind Avatar asked Jun 11 '12 13:06

CuriousMind


People also ask

What are Ruby Mixins?

Mixins in Ruby allows modules to access instance methods of another one using include method. Mixins provides a controlled way of adding functionality to classes. The code in the mixin starts to interact with code in the class. In Ruby, a code wrapped up in a module is called mixins that a class can include or extend.

What are modules in Ruby?

In Ruby, modules are somewhat similar to classes: they are things that hold methods, just like classes do. However, modules can not be instantiated. I.e., it is not possible to create objects from a module. And modules, unlike classes, therefore do not have a method new .

Can modules include other modules Ruby?

Actually, Ruby facilitates the use of composition by using the mixin facility. Indeed, a module can be included in another module or class by using the include , prepend and extend keywords.

Can modules inherit Ruby?

The Ruby class Class inherits from Module and adds things like instantiation, properties, etc – all things you would normally think a class would have. Because Module is literally an ancestor of Class , this means Modules can be treated like classes in some ways.


1 Answers

Mixins are a language concept that allows to inject some code into a class.

This is implemented in Ruby by the keyword include that takes a Module as a parameter.

So yes, in Ruby, mixins are implemented with modules. But modules have other uses than mixins.

For example, modules can also be used for namespacing your classes or encapsulating utility functions to keep from polluting the global namespace.

like image 90
Vincent Robert Avatar answered Sep 28 '22 00:09

Vincent Robert