0
0
Rubyprogramming~5 mins

Module methods in Ruby

Choose your learning style9 modes available
Introduction

Module methods let you group reusable code that can be shared across different parts of your program.

When you want to share common functions between classes without repeating code.
When you want to organize helper methods that don't belong to a specific class.
When you want to add functionality to classes by mixing in modules.
When you want to keep your code clean and easy to maintain by grouping related methods.
Syntax
Ruby
module ModuleName
  def self.method_name
    # code here
  end
end

Use self.method_name to define a method that belongs to the module itself.

You can call module methods directly with ModuleName.method_name.

Examples
This defines a module method say_hello and calls it directly.
Ruby
module Greetings
  def self.say_hello
    puts "Hello!"
  end
end

Greetings.say_hello
This module method calculates the square of a number and returns it.
Ruby
module MathHelpers
  def self.square(x)
    x * x
  end
end

result = MathHelpers.square(4)
puts result
Sample Program

This program defines two module methods: one to greet a person by name and one to add two numbers. It then calls both methods and prints their results.

Ruby
module Tools
  def self.greet(name)
    "Hello, #{name}!"
  end

  def self.add(a, b)
    a + b
  end
end

puts Tools.greet("Alice")
puts Tools.add(5, 7)
OutputSuccess
Important Notes

Module methods are like static methods in other languages.

You cannot create instances of a module, so module methods are called on the module itself.

Modules help keep your code organized and avoid repeating the same code in multiple places.

Summary

Module methods are defined with self.method_name inside a module.

You call module methods directly on the module, like ModuleName.method_name.

Use modules to group reusable code that can be shared across your program.