rubyclassoverridingclass-methodeigenclass

Ruby Class Methods vs. Methods in Eigenclasses


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?

class X
  # class method
  def self.a
    "a"
  end

  # eigenclass method
  class << self
    def b
      "b"
    end
  end
end

Do X.a and X.b behave differently in any way?

I recognize that I can overwrite or alias class methods by opening the eigenclass:

irb(main):031:0> class X; def self.a; "a"; end; end
=> nil
irb(main):032:0> class X; class << self; alias_method :b, :a; end; end
=> #<Class:X>
irb(main):033:0> X.a
=> "a"
irb(main):034:0> X.b
=> "a"
irb(main):035:0> class X; class << self; def a; "c"; end; end; end
=> nil
irb(main):036:0> X.a
=> "c"

Solution

  • 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
    #=> [#<Foo:0x2a3f020>, #<Foo:0x2a1a5c0>]
    

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

    Foo.define_singleton_method :bim do "bam!" end