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:
Syntax
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
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
Login to try C/C++/Java/PHP code in the editor
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
- Using
includewhen class-level methods are needed, soPerson.class_inforaisesNoMethodError; useextend. - Using
extendwhen instance methods are needed, so objects do not get the methods. - 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: