DesignAssembler

備忘録に近い

Rubyのincludeとexclude

簡単に言うと、includeはインスタンスメソッドとしてモジュールのメソッドが使えるようになり、extendはクラスメソッドとしてモジュールのメソッドが使えるようになります。

#include_exclude.rb
module Dog
  def dog
    puts "inu"
  end
end

module Cat
  def cat
    puts "neko"
  end
end

class Practice
  include Dog
  extend  Cat
end

Practice.new.dog
Practice.cat

#実行
$ ruby include_exclude.rb
inu
neko

includeとextendを逆にするとNoMethodErrorになります。

$ ruby include_exclude.rb
include_exclude.rb:18:in `<main>': undefined method `dog' for #<Practice:0x007feb840ac1a8> (NoMethodError)

また、extendはincludeを使って書き換えることができます。

class Practice
  include Dog
  class << self
    include Cat
  end
end

includeをクラス拡張、extendをオブジェクト拡張といいます。

railsのソース見るとinclude/excludeはずらっと並んでます。

参考

instance method Object#extend (Ruby 2.0.0)