Let’s take an example to better understand the differences.

include Foo Inside a Class

When you use include inside a class, it adds the methods from the module Foo to that class. This means that only instances of that class will have access to the module’s methods.

Example:
output

Result: greet is available to instances of MyClass

include Foo Outside a Class

When you use include outside any class, it adds the module Foo to Object’s ancestors. Since all objects inherit from Object, the methods in Foo become available for all objects.

Example:
ouput2

Result: greet is now available for all objects (like String, Array, etc.)

When to Use Each Approach

Inside the class: Use this when you want the module’s methods to be available only in specific classes.
Outside the class: Use this when you want the module’s methods to be available globally across all objects.

Conclusion

  • Inside a class: Methods are added to a specific class.
  • Outside a class: Methods are added globally to all objects.

While using include inside a class is more common and safer, using it outside can be helpful for adding shared behavior across all objects.

Support On Demand!

Ruby on Rails

Related Q&A