given
module Foo
def bar
puts "foobar"
end
end
I can do
String.extend(Foo)
and as a consequence do
String.bar # => "foobar"
Why doesnt this work?:
a = String.new
a.bar # => NoMethodError: undefined method `bar' for "":String
Is it because ‘a’ is now and instance and .extend only works against class methods? Why does it lose the ‘new’ functionality I have given String via .extend?
Ruby allows you to add methods from a Module to a Class in two ways:
extendandinclude.Using the module you gave:
With
extendthe methods are added as class methods, and can be called directly on the class object itself:Alternatively, you can call it outside of the class scope:
includeis slightly different. It will add the methods as instance methods. They are only callable on an instance of the class:The key difference was that we first had to make an instance
a, before we could call the instance method.As sepp2k noted,
extendis can be called on any Object, not just Class objects. For example, you can go:However,
barwill only be added to the single instancea. If we create a new instance, it you will not be able to call it.