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

前端 未结 6 592
囚心锁ツ
囚心锁ツ 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条回答
  •  -上瘾入骨i
    2020-11-30 21:35

    So far the question and answers only discuss these two options:

    class MyClass
      def self.method_name
        ..
      end
    end
    
    class MyClass
      class << self
        def method_name
          ..
        end
      end
    end
    

    There's a third option to consider for class methods:

    class MyClass
      def MyClass.method_name
        ..
      end
    end
    

    It's not popular and is more verbose, but it's the most explicit option.

    It's also less confusing if you mix up self behaviour between Python and Ruby.

提交回复
热议问题