3 ms·
I never understood why people prefer class << self over class self.method, the former adds more cognitive load in my opinion.
by Alifatisk 3y ago
I never understood why people prefer
class << self over class self.method, the former adds more cognitive load in my opinion.
- typeofhuman 3y agoI 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 3y 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 3y agoBoth of those work. There is also `module_function` for when you don’t want to write `self`.
- cout 3y 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.
- deleted 3y ago[deleted]
- deleted 3y ago[deleted]
- cout 3y agoI used to prefer class << self because it is less repetition. Then I discovered this led to crashes in the GC in early ruby 2.x, so I switched for a while to class self.method. Now I write an inner module ClassMethods and use extend at class scope. This I think makes it clearer that we are dealing with two distinct classes, the class and its metaclass (which is a factory).
- bdcravens 3y agoPrivate class methods
- entropie 3y agoThis should be the only reason, imho. OTOH ruby programmers have usually many ways to achieve something. I think thats inerhited from perl. Its good and bad.