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

include and extend

include mixes a module's actions into objects made from a class, while extend adds them to the class itself. It is like giving skills to every student or to the class as a whole.

In this page:

  1. include and extend
Syntax
ruby
class ClassName
  include ModuleName    # instance methods
  extend ModuleName     # class methods
end

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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using include when class-level methods are needed, so Person.class_info raises NoMethodError; use extend.
  2. Using extend when instance methods are needed, so objects do not get the methods.
  3. Forgetting that the module must be defined before it is included.
🔒

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.