Rubyモジュール - Silver/Gold試験対策
# モジュールと、クラスへのインクルード module A def fuga puts("Hello, Bob. My name is #{self.class}") end end class Alice include A def fuga super puts "Nice to Meet you" end end Alice.new.fuga #=>Hello, Bob. My name is Alice Nice to Meet you
module A def a p :a end end module B def b p :b end end class C include A include B end C.new.a #=> :a C.new.b #=> :b
# moduleをインクルードしたmoduleをインクルードしたクラス module A def a p :a end end module B include A end class C include B end C.new.a
# extend module A def hoge p :hoge end end obj = Object.new obj.extend(A) obj.hoge #=> :hoge # クラスメソッドとして動作 class B extend A end B.hoge #=> :hoge
# モジュール関数 module A def self.hoge p :hoge end end A.hoge #=> :hoge # こちらも同じ module B def hoge p :hoge end module_function :hoge end B.hoge
モジュール関数を、クラスから呼び出すと、private methodとなる
module FugaMod def fuga end module_function :fuga end class FugaClass include(FugaMod) end p FugaClass.new.fuga #=> private method `fuga' called
module_functionを引数無しで呼び出すと以降のメソッドはモジュール関数となる
module M def fuga :fuga end module_function def hoge :hoge end end class K include(M) end p K.new.fuga #=> :fuga p K.new.hoge #=> private method called (No Method Error)