CuriousMind
CuriousMind

Reputation: 34145

Are modules == mixins in 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

Upvotes: 5

Views: 841

Answers (2)

Vincent Robert
Vincent Robert

Reputation: 36130

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.

Upvotes: 13

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

From wikipedia article

In object-oriented programming languages, a mixin is a class that provides a certain functionality to be inherited or just reused by a subclass, while not meant for instantiation (the generation of objects of that class).

So yes, modules in Ruby provide a way to reuse functionality without instantiating modules themselves. I'd say, "mixins in ruby are implemented with modules", but not "mixins are modules and vice versa".

Upvotes: 5

Related Questions