Ruby Class Methods vs. Methods in Eigenclasses

前端 未结 4 987
伪装坚强ぢ
伪装坚强ぢ 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:27

    The two methods are equivalent. The 'eigenclass' version is helpful for using the attr_* methods, for example:

    class Foo
      @instances = []
      class << self;
        attr_reader :instances
      end
      def initialize
        self.class.instances << self
      end
    end
    
    2.times{ Foo.new }
    p Foo.instances
    #=> [#, #]
    

    You can also use define_singleton_method to create methods on the class:

    Foo.define_singleton_method :bim do "bam!" end
    

提交回复
热议问题