geekelo / geekelo/dsa_practice

What is the difference between extend and include in Ruby?

Open
#4 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
No language data
Stars
1
Forks
0
PR merge metrics
No merged PRs in 30d

Description

In Ruby, both `extend` and `include` are used to mix in modules into classes, but they are used in different contexts and have different effects.

1. **`include`**: This is used to mix a module's methods as instance methods in a class. When you `include` a module in a class, the methods of that module become available to instances of the class, but not to the class itself.

```ruby
module MyModule
def my_method
puts "This is a method from MyModule"
end
end

class MyClass
include MyModule
end

obj = MyClass.new
obj.my_method # This works
```

2. **`extend`**: This is used to mix a module's methods as class methods in a class. When you `extend` a module in a class, the methods of that module become available at the class level, but not to instances of the class.

```ruby
module MyModule
def my_method
puts "This is a method from MyModule"
end
end

class MyClass
extend MyModule
end

MyClass.my_method # This works
obj = MyClass.new
# obj.my_method # This would raise a NoMethodError since my_method is not available to instances
```

So, in summary:
- `include` is for mixing in instance methods.
- `extend` is for mixing in class methods.

In many cases, you might see `extend self` used within a module, which effectively makes all its methods both class methods (accessible at the class level) and instance methods (accessible at the instance level).

Contributor guide

No contributing guide indexed for this repository

Research direction

The issue names no repository file, test, or documentation entry point. First inspect the project structure to find where Ruby practice explanations are kept; the issue would be done when a specific documentation location and acceptance criteria are identified for this explanation.

Written by the indexing model from the issue text.

Assessment

Tech stack
ruby
Domain
documentation
Issue type
Documentation
Difficulty
1/5
Estimated time
Under an hour
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.