In this blog post, we’ll see what the module is, and how to use it.
The Module is a bundle of the processes, and you can define the module by the
module ModuleName ... end
The module name is started with capital.
You can distinct the Same name but different features by adding the namespace. In Ruby, You can prevent the conflict of the methods, constants, and classes name by using the module.
You can use the methods or constants provided by the module.
You can use
:: to refer to the constants and use
. for the methods of the module. If you use the module constants and methods many times, you can use
include to refer them.
include Math PI sqrt(2)
As you see above, you can use
. for the methods of the module. But simply defining a method in the module can’t be used as above.
To make the method defined in the module be used by
., you should use
module_function for them.
module Greeting def hello puts "Hello" end module_function :hello end Gretting.hello
Mix-in means that you use
include to load the module in the class.
module Greeting def hello puts "Hello" end end class World include Greeting end world = World.new world.hello
We’ve seen how to define the module and how to use it in Ruby. From now on, let’s use the Module when you need to gather the many procedures!
Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!