Module vs Class in Ruby: Key Differences and When to Use Each
class is a blueprint for creating objects and supports inheritance, while a module is a collection of methods and constants that cannot be instantiated or inherited but can be mixed into classes. Modules are mainly used for sharing reusable code, whereas classes define objects with state and behavior.Quick Comparison
Here is a quick side-by-side comparison of Ruby modules and classes based on key factors.
| Factor | Module | Class |
|---|---|---|
| Instantiation | Cannot create instances | Can create instances (objects) |
| Inheritance | Cannot inherit or be inherited | Supports single inheritance |
| Purpose | Share reusable methods/constants (mixins) | Define objects with state and behavior |
| State | Cannot hold instance variables for objects | Can hold instance variables for each object |
| Use case | Add shared behavior to classes | Model real-world entities or concepts |
| Syntax | Defined with module keyword | Defined with class keyword |
Key Differences
A class in Ruby is a blueprint for creating objects. It can have instance variables, methods, and supports inheritance, meaning one class can inherit behavior from another. You create objects (instances) from classes using .new. Classes model entities with both data and behavior.
On the other hand, a module is a container for methods, constants, and other modules. It cannot be instantiated or subclassed. Instead, modules are used to share reusable code by mixing them into classes using include or extend. This helps avoid duplication and supports multiple inheritance-like behavior.
In summary, use classes when you need to create objects with state and behavior, and use modules to group related methods and constants that can be shared across multiple classes.
Code Comparison
This example shows a class defining a simple object with state and behavior.
class Dog def initialize(name) @name = name end def bark "#{@name} says Woof!" end end dog = Dog.new("Buddy") puts dog.bark
Module Equivalent
This example shows a module used to share behavior that can be mixed into any class.
module Barkable
def bark
"#{name} says Woof!"
end
end
class Dog
include Barkable
attr_reader :name
def initialize(name)
@name = name
end
end
dog = Dog.new("Buddy")
puts dog.barkWhen to Use Which
Choose a class when you want to create objects that hold their own data and behavior, especially if you need inheritance to model relationships.
Choose a module when you want to share reusable methods or constants across multiple classes without creating objects or inheritance. Modules are perfect for mixins to add shared behavior.
In short, use classes for object modeling and modules for code sharing.