What is the difference between include and extend in Ruby?


Include vs Extend: Demystifying Ruby Mixins
<p>🤔 Just getting my head around Ruby metaprogramming. The mixin/modules always manage to confuse me. </p>
<p>So, what is the difference between include and extend in Ruby? Let's break it down! 🕵️♀️</p>
The Basics: Include and Extend
<ul> <li><strong>include</strong>: mixes in specified module methods as <strong>instance methods</strong> in the target class</li> <li><strong>extend</strong>: mixes in specified module methods as <strong>class methods</strong> in the target class</li> </ul>
<p>Essentially, when you include a module in a class, you are adding the module's methods as instance methods in that class. On the other hand, when you extend a class with a module, you are adding the module's methods as class methods in that class. 🎭</p>
🐉 A Bigger Dragon?
<p>Now, you may wonder if there's a bigger, hidden dragon behind this apparent simplicity. Let's find out! 🔍</p>
<pre><code>module ReusableModule def module_method puts "Module Method: Hi there!" end end class ClassThatIncludes include ReusableModule end class ClassThatExtends extend ReusableModule end puts "Include" ClassThatIncludes.new.module_method # "Module Method: Hi there!" puts "Extend" ClassThatExtends.module_method # "Module Method: Hi there!" </code></pre>
<p>As you can see from the code snippet above, when we include <code>ReusableModule</code> in <code>ClassThatIncludes</code>, we can directly call <code>module_method</code> on an instance of <code>ClassThatIncludes</code>.</p>
<p>Similarly, when we extend <code>ClassThatExtends</code> with <code>ReusableModule</code>, we can call <code>module_method</code> directly on the class itself, without creating any instances. 🎉</p>
Conclusion
<p>And that's the difference between include and extend in Ruby! 🎈</p>
<p>Use include when you want to add module methods as instance methods in a class, and extend when you want to add module methods as class methods in a class.</p>
<p>With this knowledge in hand, you can now confidently wield the power of mixins in your Ruby code. Happy coding! 💻</p>
<p>Got any other Ruby questions? Want to share your mixin adventures? Leave a comment below and let's start a conversation! 🗣️</p>
Take Your Tech Career to the Next Level
Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.
