← Back to Ruby Course | Chapter 10: Modules & Mixins | Lesson 2 of 6

include and extend

In this page:

  1. include and extend

include and extend

include ModuleName inside a class mixes the module's methods in as instance methods, available on objects of that class. extend ModuleName instead mixes them in as methods on the class itself (or a specific object), similar to adding static/class methods. Choosing between them depends on whether the behavior belongs to individual instances or to the class as a whole.

Note: include gives instance methods (available on objects); extend gives methods directly on the class or a single object.

Example: include and extend

markup
module Describable
  def describe
    puts "This is a #{self.class}"
  end
end

module ClassHelpers
  def class_info
    puts "Class: #{name}"
  end
end

class Widget
  include Describable
  extend ClassHelpers
end

Widget.new.describe
Widget.class_info
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.