Ruby Module

Module are used to combine class methods and constant objects. The main goal of module are provide the solution of ambiguity of name problem. And module method is shareable by other classes which are include this module. And this are avoid repetition of code.

module ModuleName

  # module statements

end

module keyword are used to define a module in ruby followed by the name of module. That declaration is similar to class but module are cannot create any object and not be inherited.

Define Module method

There are two type of method define are possible inside a ruby module. First is simple module methods which are defined of module name (or self) and dot operator. This type of method always use by module name. And second is defined simple method which is used by class objects. But first to need to including this module to particular class. Let see an example.

module Test

  #module method
  def Test.test_one
    puts "Test One"
  end
  #class instance method
  def test_two
    puts "Test Two"
  end
end

Test.test_one #Test One

#Test.test_two #Not work
Test One

In this example test_two is a class method that is not use by module name but that is used when including this module to an class .

include statement are used to import a module into an class. And class object is capable to use instance method of module. See this example.

module Test

  #module method
  def Test.test_one
    puts "Test One"
  end
  #class instance method
  def test_two
    puts "Test Two"
  end
end

class Result
  #include module
  include Test

  def info
    puts "Class info method"
    Test.test_one #execute module method
    
  end
end

obj = Result.new();
obj.test_two
obj.info
Test Two
Class info method
Test One

Define and use constant variable

module Test
  PI = 3.1415
  #module method
  def Test.test_two
    puts "PI #{PI}"
  end
end
puts Test::PI #Access Value
Test.test_two
3.1415
PI 3.1415

Module to module interface

module TestController
    @name = 'Test'
    def self.info 
      @name 
    end
  
end

module Detail
  def self.info
    puts TestController.info
  end
end

Detail.info
Test

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved