美文网首页
ruby extend、include、prepend浅析

ruby extend、include、prepend浅析

作者: 痞老板丶 | 来源:发表于2016-12-10 20:39 被阅读0次

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浅析

      本文链接:https://www.haomeiwen.com/subject/syziuttx.html