class << self vs self.method with Ruby: what's better?

前端 未结 6 609
囚心锁ツ
囚心锁ツ 2020-11-30 21:33

This Ruby Style Guide tells that is better using self.method_name instead of class method_name. But Why?

class TestClass
  # bad
           


        
6条回答
  •  庸人自扰
    2020-11-30 21:55

    Whichever you want. Both are very clear for what you do. But I think of some recommendations for this.

    When there're only one class method to define, Use def self.xxx. Because for defining only one method, increasing indent level probably become cluttering.

    When there're more than one class method to define, Use class << self. Because writing def self.xxx, def self.yyy and def self.zzz is certainly repetition. Create a section for these methods.

    When all methods in a class are class method, you can use module with module_function instead of class. This let you define module functions just use def xxx.

提交回复
热议问题