views:

47

answers:

2

In what sort of situation is the code:

module M
   extend self
   def greet
    puts "hello"
   end

end

more beneficial to use over say something like:

module M
   def self.greet
    puts "hello"
   end
end

In the top, one is an instance method being extended, and the latter is just a class method, but when calling either method, you'd have to M.greet , right? I was just curious if anyone could shed some light on when to use one code over the other. Thanks!

+3  A: 

It would be possible to do this with your first example, but not your second:

include M
greet
Adrian
Whoever upvoted this, thank you. Normally I wouldn't say this, but your upvotes pushed my reputation above 2000, causing me to be able to edit other people's posts and cause havoc on stack overflow. :)
Adrian
+1  A: 

The first example is typically a way people achieve the functionality of module_function (when they do not know the existence of this method).

A module_function is both an instance method and a class method. In your second code example the method is just a class method.

banister
Oh, that's a cool method. That way you can select which methods to give the functionality to in case you don't want to give it to all of them. Thanks!
japancheese