Introduction
Modules help group related methods and constants together. They keep code organized and avoid repeating code.
Modules help group related methods and constants together. They keep code organized and avoid repeating code.
module ModuleName # code here end
Module names start with a capital letter and use CamelCase.
Use end to close the module block.
Greetings with a method hello.module Greetings def hello puts "Hello!" end end
PI that can be used elsewhere.module MathHelpers PI = 3.14 end
module Outer module Inner def self.info puts "Inside Inner module" end end end
This program defines a module Tools with a method greet that returns a greeting message. We call it and print the result.
module Tools def self.greet(name) "Hello, #{name}!" end end puts Tools.greet("Alice")
You cannot create instances of modules like classes.
Modules are often used with include or extend to add methods to classes.
Modules group related code and constants.
Use module Name ... end to declare a module.
Modules help organize code and share behavior without inheritance.
MathTools in Ruby?module followed by the module name and end.module MathTools ... end, which is the correct syntax for a module.module Name ... end [OK]module ... end without braces { }.{ } which is invalid syntax for module declaration in Ruby.module Greetings
def self.say_hello
"Hello!"
end
end
puts Greetings.say_hellosay_hello is defined as a module method using self., so it can be called on the module directly.Greetings.say_hello returns the string "Hello!", which is printed by puts.module Tools
def help
"Help message"
end
end
Tools.helphelp is defined as an instance method, but called on the module directly.Tools.help, help must be a module method defined with self.help.Inner inside module Outer in Ruby?module Outer # Your code here end
module inside another.module Inner inside module Outer using indentation and end keywords.Pass the test and this pattern moves unknown