Rubyの「include」と「prepend」の違いは何ですか?
概要
モジュールから
以下の質問を理解するのを手伝ってくれる人はいますか?
解決策
引用したテキストに明記されているように、
どちらも、渡されたモジュール (クラス) に混合モジュールのメソッドを追加します。違いは、ターゲット クラスに既にメソッドが定義されている場合の、これらのメソッドの検索順序にあります。
include は、ターゲット クラスが混合モジュールを継承したかのように動作します。
module FooBar
def say
puts "2 - Module"
end
end
class Foo
include FooBar
def say
puts "1 - Implementing Class"
super
end
end
Foo.new.say # =>
# 1 - Implementing Class
# 2 - Module
prepend は、混合モジュールのメソッドを「より強力」にし、最初に実行します。
module FooBar
def say
puts "2 - Module"
super
end
end
class Foo
prepend FooBar
def say
puts "1 - Implementing Class"
end
end
Foo.new.say # =>
# 2 - Module
# 1 - Implementing Class
この例は、ここから転載したものです: http://blog.crowdint.com/2012/11/05/3-killer-features-that-are-coming-on-ruby-2-0.html
ターゲット モジュール (クラス) のメソッドをメソッド検索チェーンの最後に保持したい場合は、prepend を使用します。
実際の例は、SO で Ruby、module、prepend を検索すると見つかります。
(注: 継承と混合に関してはメソッドが最もイメージしやすいため、メソッドのみについて言及していますが、他の機能にも同じことが当てはまります。)