user413881
user413881

Reputation: 225

Metaclass in Ruby

I wrote a code (for the experiment:)):

class A
  class << self
    def self.f
      puts "f"
    end

    def getMetaclass
      class << self
        self
      end  
    end
  end
end

A.getMetaclass.f

I understand that metaclass have their metaclass. Сorrect?

Upvotes: 1

Views: 321

Answers (2)

Andrew Grimm
Andrew Grimm

Reputation: 81510

I've read that eigenclasses are only created when they're required. If so, then it's possible to have a "Turtles all the way down" approach.

Upvotes: 0

mliebelt
mliebelt

Reputation: 15525

In the book "Metaprogramming Ruby" of Paolo Perrotta, the term metaclass is only mentioned once, instead the term "eigenclass" is used more often. The eigenclass of class A in your example is the metaclass, and it has its own metaclass (not metaclasses). So I have tried to expand your example, and it seems that this chain never ends:

class Eigen
  class << self
    def getMetaclass
      self
    end

    def getMetaMetaClass
      class << self
        self
      end
    end

    def getMetaMetaMetaClass
      class << self
        class << self
          self
        end
      end
    end

  end
end

if __FILE__ == $0
  puts Eigen.getMetaclass
  puts Eigen.getMetaMetaClass
  puts Eigen.getMetaMetaMetaClass
end

The result here is:

ruby eigen.rb

Eigen
#<Class:Eigen>
#<Class:#<Class:Eigen>>

I only cannot see what to do with such constructions :-)

Upvotes: 3

Related Questions