Ruby Language Modules A simple mixin with include

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

module SomeMixin
  def foo
    puts "foo!"
  end
end

class Bar
  include SomeMixin
  def baz
    puts "baz!"
  end
end

b = Bar.new
b.baz         # => "baz!"
b.foo         # => "foo!"
# works thanks to the mixin

Now Bar is a mix of its own methods and the methods from SomeMixin.

Note that how a mixin is used in a class depends on how it is added:

  • the include keyword evaluates the module code in the class context (eg. method definitions will be methods on instances of the class),
  • extend will evaluate the module code in the context of the singleton class of the object (methods are available directly on the extended object).


Got any Ruby Language Question?