include
include use for adding methods to an instance of a class.
example
example
1234567891011121314
moduleFoodeffoop'Hi foo'endendclassBarincludeFooendbar=Bar.newbar.foo# => Hi fooBar.foo# => NoMethodError: undefined method ‘foo’ for Bar:Class
extend
extend use for adding class methods.
example
example
1234567891011121314
moduleFoodeffoop'Hi foo'endendclassBazextendFooendBar.foo# => Hi foobar=Bar.newbar.foo# => NoMethodError: undefined method ‘foo’ for #<Baz:0x1e708>
Using include to append both class and instance methods
You will see in Ruby is to use include to append both class and instance methods.
The reason for this is that include has a self.included hook you can use to modify
the class that is including a module.
example
example
12345678910111213141516171819202122232425
moduleFoodefself.included(base)base.extend(ClassMethods)endmoduleClassMethodsdefbarp'class method'endenddeffoop'instance method'endendclassBarincludeFooendBar.bar# => class methodBar.foo# => NoMethodError: undefined method ‘foo’ for Baz:ClassBar.new.foo# => instance methodBar.new.bar# => NoMethodError: undefined method ‘bar’ for #<Baz:0x1e3d4>