Introduction
Modules help keep your code organized by grouping related things together. They also prevent name clashes when different parts of your program use the same names.
Modules help keep your code organized by grouping related things together. They also prevent name clashes when different parts of your program use the same names.
module ModuleName # code here end
module keyword followed by the module name starting with a capital letter.Greetings.say_hello.module Greetings def self.say_hello puts "Hello!" end end
Birds inside Animals to organize related code.module Animals module Birds def self.info puts "Birds can fly." end end end
Hammer is inside the Tools module to avoid name clashes with other Hammer classes.module Tools class Hammer def hit puts "Bang!" end end end
This program defines a Toaster class inside nested modules Kitchen and Appliances. We create a new toaster and call its toast method.
module Kitchen module Appliances class Toaster def toast puts "Toasting bread!" end end end end toaster = Kitchen::Appliances::Toaster.new toaster.toast
Use :: to access classes or modules inside modules.
Modules cannot be instantiated like classes; they are containers for code.
Modules can also be used to mix in methods to classes using include or extend.
Modules group related code and prevent name conflicts.
Use nested modules for better organization.
Access nested code with the :: operator.
MathTools::Algebra in Ruby?module keywords and end statements.module MathTools; module Algebra; end; end correctly uses two module blocks nested inside each other. Other options use invalid syntax such as dots, colons, or commas.module Outer
module Inner
def self.greet
"Hello from Inner"
end
end
end
puts Outer::Inner.greetgreet is defined as a class method on the nested module Inner.Outer::Inner.greet correctly accesses the method and returns the string.module A
module B
def greet
"Hi"
end
end
end
puts A::B.greetgreet is an instance method but is called on the module itself.A::B.greet expects a class method, but greet is an instance method, causing a NoMethodError.calculate method from outside the modules?module Finance
module Tax
def self.calculate(amount)
amount * 0.15
end
end
endcalculate is a class method inside nested modules Finance and Tax.:: operator to access nested modules and call the class method with dot notation.Pass the test and this pattern moves unknown