include and extend
In this page:
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
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: