ruby extend、include、prepend浅析

include与extend

module A
  def my_method
    'method in module A'
  end
end

class B
  include A
end

class C
  extend A
end

puts B.new.my_method #=> method in module A
# puts C.new.my_method # error undefined method
puts C.my_method  # => method in module A

p B.ancestors #[B, A, Object, Kernel, BasicObject]
p C.ancestors #whitout A,  [C, Object, Kernel, BasicObject]

使用include的时候,将module A加入到class B的祖先链中,而在class C的祖先链中却没有。
 使用include加入到类中,方法是实例方法,而使用extend 却成为了类方法。

prepend 与 include

module A
  def my_method
    'method in module A'
  end
end

class B
  include A
end

class C
  prepend A
end

puts B.new.my_method
puts C.new.my_method 

p B.ancestors #=> [B, A, Object, Kernel, BasicObject]
p C.ancestors #=> [A, C, Object, Kernel, BasicObject]

include与prepend都是成为实例方法,只是在祖先链中的顺序不同。

include

module A1
end
module A2
  include A1
end
class B
  include A2
end

p B.ancestors #=> [B, A2, A1, Object, Kernel, BasicObject]

你可能感兴趣的:(ruby extend、include、prepend浅析)