ITeye博客

[转]ruby的include与extend

biyeah · 2011-12-20 05:09 · Ruby · 编程语言 · Markdown

原文http://www.cnblogs.com/rubylouvre/archive/2010/03/31/1701813.html 作者:司徒正美

ruby提供了强大的继承机制,有关继承的方法很多。最简单就是“<<”,但还可以对要继承的东西进行细分,是把它添加到类中呢,还是实例中,这正是本文要介绍的内容。

module Foo
  def foo
    puts 'heyyyyoooo!'
  end
end
 
class Bar
  include Foo
end
 
Bar.new.foo # heyyyyoooo!
Bar.foo # NoMethodError: undefined method ‘foo’ for Bar:Class
 
class Baz
  extend Foo
end
 
Baz.foo # heyyyyoooo!
Baz.new.foo # NoMethodError: undefined method ‘foo’ for #<baz:0x1e708>
</baz:0x1e708>

我们可以看到通过包含(include),为目标类添加一些实例方法。而扩展则恰恰相反,为目标类添加相应的类方法。虽然同是一个模块,但方法的不同,会产生不同的效果。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。