Rubyのmoduleを使って定義したmethodは、インスタンスmethod内で使える。クラスmethod内では使えない。
include先のクラスにて、インスタンスメソッド内で使う
module Hoge def hello puts 'hello' end end class Fuga include Hoge def call_mod_method # インスタンスメソッド hello end end fuga = Fuga.new fuga.call_mod_method
Hoge moduleをincludeしてFugaクラス内でインスタンスメソッドとして使ってます。
結果
hello
ふむ。普通に使える。
include先のクラスにて、クラスメソッド内で使う
module Hoge def hello puts 'hello' end end class Fuga include Hoge def self.call_mod_method # クラスメソッド hello end end Fuga.call_mod_method
結果
`call_mod_method': undefined local variable or method `hello' for Fuga:Class (NameError)
おおー。hello methodは定義されていない、と出たぞ。
原因
「クラス内にmoduleをincludeする」
というのは、
「そのクラスにインスタンスmethodを追加する」
ということらしい(たのしいRubyより)。
今回、moduleで追加したhelloというインスタンスメソッドを、
クラスメソッドから呼び出してしまったので、そんなもんはねぇよ。
と怒られてしまった。
まとめ
Ruby結構面白いな。