Trying to understand metaclasses
2011-03-23 00:18:43
2011-03-23 00:12:24
Autor: Sony Santos
https://gigawiki.com/sony/trying-to-understand-metaclasses
Permalink: https://gigawiki.com/972
language = English, Ruby
class A
  def self.aa
    puts 'a'
  end
  class << self
    def ab
      puts 'b'
    end
  end
end

def mets(x); puts x.methods.select{|m| m=~/^a.$/}.sort.join(', '); end
def imets(x); puts x.instance_methods.select{|m| m=~/^a.$/}.sort.join(', '); end

a = A.new

def A.ac
  puts 'c'
end

class A
  def self.ad
    puts 'd'
  end
end

class << a
  def self.ae
    puts 'e'
  end
end

class << A
  def af
    puts 'f'
  end
end

mets A
mets a.eigenclass
imets a.metaclass
imets A.eigenclass
imets a.eigenclass.eigenclass

Conclusion: Class methods defined in A are not A methods; they're A eigenclass methods (= A instance metaclass methods).

Instance methods defined in A are A methods or A instance eigenclass methods? => Answer: A methods.
blog comments powered by Disqus