動機

寫寫ruby奇妙的繼承

但原本寫好的metaclass的文居然失蹤了!!!

我找不到….

之後會補….

因為原本寫metaclass的文章不見了,所以只好臨時補一個來說明metaclass

其實大家都是instance 結構大概像

struct instance { // a.k.a. metaclass
	instance* _meta; // only storing sigleton methods
	instance* _class;
	instance* _parent_class;
	vector<Val> _i_vals;
	vector<Symbol> _i_vars;
	Map<Symbol, Method> _m_env;
};

所以 instance method是 _class 的 _m_env class method是 _class 的 _meta 的 _m_env singleton method是 _meta 的 _m_env

這裡的metaclass是一種資料結構 在python的metaclass是這裡的_class(是什麼class) 在ruby的metaclass是這裡的_meta(多出來放東西的地方)

inheritance

在用parent class的m-env擴張child class的m-env的同時

因為child class有了到parent class的ref,就可以使用parent class的singleton method

class A
  def self.a
    p "a"
  end

  def b
    p "b"
  end
end

class B < A
  a
  p "x"
  self.a
end

x = B.new
x.b
=begin
a
x
a
b
=end

include & extend

class與module的差異在一個只能繼承,一個只能include與extend

被include與extend的method都只看m-env的部分,就是instance method的部分

extend就是擴充該實體instance的class的meta中的m-env (class method) include就是擴充該實體instance的m-env (instance method)

module InstanceMethods
  def self.A
    "in A"
  end

  def an_instance_method
    "You called an_instance_method on #{self.class}"
  end

  def self.included(base)
    p "from include"
  end
end

module ClassMethods
  def self.B
    "in B"
  end

  def a_class_method
    "You called a_class_method_from_module on #{self}"
  end

  def self.extended(base)
    p "from extend"
  end
end

class MyClass
  include InstanceMethods
  extend ClassMethods
end

my_class = MyClass.new
puts my_class.an_instance_method # >> You called an_instance_method on MyClass
#puts my_class.A
#puts my_class.B
puts MyClass.a_class_method      # >> You called a_class_method on MyClass
#puts MyClass.A
#puts MyClass.B

obj = Object.new
obj.extend InstanceMethods
puts obj.an_instance_method

Ref

Extending your include knowledge of Ruby Ruby Sub-Classes/Inheritance, Include, And Extend