Mixin (Ruby)

A mixin is a module of methods included into a class to share behavior without inheritance. Ruby uses mixins via include and extend to compose functionality across unrelated classes.

Ruby

Ruby has single inheritance — a class has one superclass — but unlimited mixins. By putting shared methods in a module and writing include SomeModule in a class, those methods become available to instances as if defined in the class. This is how Ruby achieves multiple-inheritance-like reuse safely.

The two best-known standard mixins are Comparable (define <=> and get <, >, ==, between?, etc. for free) and Enumerable (define each and get map, select, sort, and dozens more). Your own modules can be mixed in the same way.

include adds methods as instance methods; extend adds a module's methods to a single object or as class methods. prepend inserts the module ahead of the class in the lookup chain. Mixins favor composition over deep inheritance hierarchies.

Syntax

module Greet
  def hello; "hi from #{name}"; end
end
class User; include Greet; end

Examples

Ruby

module Walkable
  def walk; "#{name} is walking"; end
end

class Person
  include Walkable
  attr_reader :name
  def initialize(n); @name = n; end
end

puts Person.new("Ada").walk

Output:

Ada is walking

Learn it in a lesson

See also

Back to the Dictionary