This Ruby Style Guide tells that is better using self.method_name
instead of class method_name
. But Why?
class TestClass # bad class << self def first_method # body omitted end def second_method_etc # body omitted end end # good def self.first_method # body omitted end def self.second_method_etc # body omitted end end
Are there performance issues?
In the above example, class << self modifies self so it points to the metaclass of the Zabuton class. When a method is defined without an explicit receiver (the class/object on which the method will be defined), it is implicitly defined within the current scope, that is, the current value of self.
In Ruby, a method provides functionality to an Object. A class method provides functionality to a class itself, while an instance method provides functionality to one instance of a class. We cannot call an instance method on the class itself, and we cannot directly call a class method on an instance.
What is the difference between a class and a module? Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables).
the method self refers to the object it belongs to. Class definitions are objects too. If you use self inside class definition it refers to the object of class definition (to the class) if you call it inside class method it refers to the class again.
class << self
is good at keeping all of your class methods in the same block. If methods are being added in def self.method
form then there's no guarantee (other than convention and wishful thinking) that there won't be an extra class method tucked away later in the file.
def self.method
is good at explicitly stating that a method is a class method, whereas with class << self
you have to go and find the container yourself.
Which of these is more important to you is a subjective decision, and also depends on things like how many other people are working on the code and what their preferences are.
Generally, class << self
is used in metaprogramming to set the class as self for a prolonged period of time. If I'm trying to write 10 methods, I would use it like so:
METHOD_APPENDICES = [1...10] class << self METHOD_APPENDICES.each do |n| define_method("method#{n}") { n } end end
This would create 10 methods (method1, method2, method3, etc.) that would just return the number. I would use class << self
for clarity in this case because in metaprogramming self
is crucial. Littering self.
inside there would actually make things less readable.
If you're just defining class methods normally, stick to self.class_method_name
because more people are likely to understand it. No need to bring in meta-syntax unless you expect your audience to understand it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With