Ruby - Module Module Functions

Introduction

To make a function both as an instance and as a module method, use the module_function method with a symbol matching the name of an instance method:

module MyModule
     def sayHi
         return "hi!"
     end

     def sayGoodbye
         return "Goodbye"
     end

     module_function :sayHi
end

The sayHi method may now be mixed into a class and used as an instance method:

class MyClass
     include MyModule
         def speak
             puts(sayHi)
             puts(sayGoodbye)
         end
end

It may be used as a module method, using dot notation:

ob = MyClass.new
ob.speak                   #=> hi!\nGoodbye
puts(MyModule.sayHi)       #=> hi!

Related Topic