3 ms·
I think this is to allow you to define class methods on modules that can be called directly. I think the Math module does this. module Foo def self.bar
by typeofhuman 2y ago
I think this is to allow you to define class methods on modules that can be called directly. I think the Math module does this.
module Foo
def self.bar
"Baz"
end
end
Foo.bar # won't work
module Foo
class << self
def bar
"Baz"
end
end
end
Foo.bar # works
- vidarh 2y agoThis is conceptually no different from metaclasses for other objects. The reason for this is that the class object for module Foo is Module. You have no way of specifying that the class object for a class or module should be anything other than Class or Module. But you can insert methods into the metaclass of the Foo Module object.
- breckenedge 2y agoBoth of those work. There is also `module_function` for when you don’t want to write `self`.
- cout 2y agomodule_function is different in that it makes the method both a class method (i.e. an instance method on the singleton class) and a private instance method (so you can call the method with implicit self). Once upon a time a used this a lot because it felt conceptually similar to a C++ static member function, but I rarely use it any more.