Just as you can define an anonymous class for an
object using ``
class <<obj
'', you can mix a module into an
object using
Object#extend
. For example:
module Humor
|
def tickle
|
"hee, hee!"
|
end
|
end
|
|
a = "Grouchy"
|
a.extend Humor
|
a.tickle
|
� |
"hee, hee!"
|
There is an interesting trick with
extend
.
If you use it
within a class definition, the module's methods become class
methods.
module Humor
|
def tickle
|
"hee, hee!"
|
end
|
end
|
|
class Grouchy
|
include Humor
|
extend Humor
|
end
|
|
Grouchy.tickle
|
� |
"hee, hee!"
|
a = Grouchy.new
|
a.tickle
|
� |
"hee, hee!"
|
This is because calling
extend
is equivalent to
self.extend
, so the methods are added to
self
, which in a
class definition is the class itself.