0
0
Rubyprogramming~5 mins

Include for instance methods in Ruby

Choose your learning style9 modes available
Introduction

Including a module lets you add shared behaviors to many classes easily. It helps keep your code organized and avoids repeating the same methods.

You want to share the same methods across different classes without copying code.
You have helper methods that many objects should use.
You want to add features to objects without changing their original class.
You want to keep your code clean by grouping related methods together.
Syntax
Ruby
module ModuleName
  def method_name
    # method code
  end
end

class ClassName
  include ModuleName
end

Use include inside a class to add instance methods from a module.

Methods from the module become available as instance methods of the class.

Examples
This example adds a say_hello method to Person instances using include.
Ruby
module Greetings
  def say_hello
    "Hello!"
  end
end

class Person
  include Greetings
end

p = Person.new
puts p.say_hello
Here, Calculator instances get the square method from the MathHelpers module.
Ruby
module MathHelpers
  def square(x)
    x * x
  end
end

class Calculator
  include MathHelpers
end

calc = Calculator.new
puts calc.square(5)
Sample Program

This program shows how including the Talk module adds the speak method to Dog instances.

Ruby
module Talk
  def speak
    "I can talk!"
  end
end

class Dog
  include Talk
end

my_dog = Dog.new
puts my_dog.speak
OutputSuccess
Important Notes

If you use include multiple times, later modules can override methods from earlier ones.

Modules included this way add instance methods, not class methods.

Summary

Include adds module methods as instance methods to a class.

It helps share code between classes without repeating it.

Use it to keep your code organized and DRY (Don't Repeat Yourself).