0
0
Rubyprogramming~5 mins

Extend for class methods in Ruby

Choose your learning style9 modes available
Introduction

We use extend to add methods from a module directly to a class as class methods. This helps share behavior without repeating code.

When you want to add utility methods to a class itself, not its instances.
When you want to organize related class methods in a module.
When you want to share class-level behavior across multiple classes.
When you want to keep your code clean by separating instance and class methods.
Syntax
Ruby
module ModuleName
  def method_name
    # code
  end
end

class ClassName
  extend ModuleName
end

extend adds module methods as class methods.

Use include to add methods as instance methods instead.

Examples
This example adds say_hello as a class method to Person.
Ruby
module Greetings
  def say_hello
    "Hello from class!"
  end
end

class Person
  extend Greetings
end

puts Person.say_hello
Here, square becomes a class method of Calculator.
Ruby
module MathHelpers
  def square(x)
    x * x
  end
end

class Calculator
  extend MathHelpers
end

puts Calculator.square(5)
Sample Program

This program shows how log is used as a class method on Application by extending Logger.

Ruby
module Logger
  def log(message)
    "LOG: #{message}"
  end
end

class Application
  extend Logger
end

puts Application.log("Starting app")
OutputSuccess
Important Notes

Remember, extend adds methods to the class itself, not to instances.

You can extend multiple modules to add many class methods.

Using extend keeps your class methods organized and reusable.

Summary

extend adds module methods as class methods.

Use it to share behavior across classes without repeating code.

It helps keep instance and class methods separate and clear.