How to Include Module in Ruby: Syntax and Examples
In Ruby, you include a module into a class using the
include keyword followed by the module name. This adds the module's methods as instance methods to the class, allowing you to reuse code easily.Syntax
Use the include keyword inside a class to add a module's methods as instance methods. The module name follows include.
- include: keyword to add module methods
- ModuleName: the module you want to include
ruby
module Greetings
def hello
"Hello!"
end
end
class Person
include Greetings
endExample
This example shows a module Greetings with a method hello. The class Person includes this module, so its instances can call hello.
ruby
module Greetings
def hello
"Hello!"
end
end
class Person
include Greetings
end
person = Person.new
puts person.helloOutput
Hello!
Common Pitfalls
One common mistake is trying to call module methods directly on the class without including the module. Another is confusing include with extend, which adds methods as class methods instead of instance methods.
ruby
module Greetings
def hello
"Hello!"
end
end
class Person
# Wrong: calling module method without include
# puts hello # Error: undefined method
# Correct: include module to use instance methods
include Greetings
end
person = Person.new
puts person.helloOutput
Hello!
Quick Reference
| Keyword | Purpose |
|---|---|
| include ModuleName | Adds module methods as instance methods to a class |
| extend ModuleName | Adds module methods as class methods to a class |
| ModuleName.method_name | Call module method directly if defined as module method |
Key Takeaways
Use
include ModuleName inside a class to add module methods as instance methods.Including a module allows code reuse by sharing methods across classes.
Do not confuse
include (instance methods) with extend (class methods).You must include the module before calling its methods on class instances.
Modules help organize and share behavior without inheritance.