Ruby Class Methods vs. Methods in Eigenclasses

前端 未结 4 964
伪装坚强ぢ
伪装坚强ぢ 2021-02-19 08:17

Are class methods and methods in the eigenclass (or metaclass) of that class just two ways to define one thing?

Otherwise, what are the differences?

cla         


        
4条回答
  •  走了就别回头了
    2021-02-19 08:38

    Yet another necromancer here to unearth this old question... One thing you might not be aware of is that marking a class method as private (using the private keyword instead of :private_class_method) is different than marking an eigenclass method as such. :

    class Foo
      class << self
        def baz
          puts "Eigenclass public method."
        end
    
        private
        def qux
          puts "Private method on eigenclass."
        end
      end
      private
      def self.bar
        puts "Private class method."
      end
    end
    
    Foo.bar
    #=> Private class method.
    Foo.baz
    #=> Eigenclass public method.
    Foo.qux
    #=> NoMethodError: private method `qux' called for Foo:Class
    #   from (irb)
    

    The following example will work how the previous one intends:

    class Foo
      class << self
        def baz
          puts "Eigen class public method."
        end
    
        private
        def qux
          puts "Private method on eigenclass."
        end
      end
      def bar
        puts "Private class method."
      end
      private_class_method :bar
    end
    Foo.bar
    #=> NoMethodError: private method `bar' called for Foo:Class
    #     from (irb)
    Foo.baz
    #=> Eigen class public method.
    Foo.qux
    #=> NoMethodError: private method `qux' called for Foo:Class
    #     from (irb)
    

提交回复
热议问题