module MyModule
def my_method; 'hello'; end
end
class MyClass
class << self
include MyModule
end
end
MyClass.my_method # => "hello
I’m unsure why “include MyModule” needs to be in the singleton class in order to be called using just MyClass.
Why can’t I go:
X = MyClass.new
X.my_method
include ModuleNameadds the methods from the module as instance methods to the including class.So if you write
then
my_methodbecomes an instance method onMyClasse.g.When you include the module inside the singleton class the methods are still being added as instance methods but to the instance of the class
Classfor your class. Therefore they appear as class methods onMyClass.EDIT (Jörg W Mittag): However, you should never do that, since
includingin the singleton class is the same asextendingthe original object, which is preferred. So, this:is the same as this:
You should always use the latter form.
More generally, this:
is the same as this:
EDIT (MAL): If you want to have you method both as an instance method and a method, you can simply define your method as above, and either
extend selfwhich will bring all instance methods accessible to the module object itself, or alternatively usemodule_function :my_method.