Full Stack Founder · a live cohort for developersjoin the waitlist →
← Back to Blog
interviewThibault “Tibo” Denizet

Include vs Extend in Ruby

Fourth article in the Prepare for a Ruby job interview series. In this article, we will study Include and Extend and see the differences between those two.

There is a big difference between include and extend in Ruby. Let me show you some code to explain it :

module Printable
  def self.class_method_x
    p 'class_method_x'
  end

  def instance_method_y
    p 'instance_method_y'
  end
end

--

class ExtendDocument
  extend Printable
end

--

class IncludeDocument
  include Printable
end

First round, on the Printable module :

Printable.class_method_x
# => "class_method_x"

--

Printable.instance_method_y
# => NoMethodError: undefined method `instance_method_y' for Printable:Module

Second round, on ExtendDocument :

ExtendDocument.class_method_x
# => NoMethodError: undefined method `class_method_x' for ExtendDocument:Class

--

ExtendDocument.instance_method_y
# => "instance_method_y"

And on an instance of ExtendDocument :

ExtendDocument.new.class_method_x
# => NoMethodError: undefined method `class_method_x' for #<ExtendDocument:0x007fe9e308ac08>

--

ExtendDocument.new.instance_method_y
# => NoMethodError: undefined method `instance_method_y' for #<ExtendDocument:0x007fe9e3080370>

Oops, nothing is working !

Last round, on IncludeDocument :

IncludeDocument.class_method_x
# => NoMethodError: undefined method `class_method_x' for IncludeDocument:Class

IncludeDocument.instance_method_y
# => NoMethodError: undefined method `instance_method_y' for IncludeDocument:Class

And on an instance of IncludeDocument :

IncludeDocument.new.class_method_x
# => NoMethodError: undefined method `class_method_x' for #<IncludeDocument:0x007fe9e3056480>

IncludeDocument.new.instance_method_y
# => "instance_method_y"

As you've probably noticed, Extend a module inside a class will add the instance methods defined in the module to the extended class.

The Include will add the instance methods defined in the module to the instances of the class including the module.

If you're still not sure about the difference, take a closer look at the examples.

Continue to the fifth part about Ruby loops .

$ whoami

Tibo, creator of Devmystify

Tibo

Hi, I'm the creator of Devmystify and author of Modular Rails and Master Ruby Web APIs.

I built a 6-figure consulting business while living in Thailand and now share practical advice on turning dev skills into a business: consulting, digital products, and SaaS.

join the cohort waitlist →

Comments

Loading comments...

> one email a week, real numbers

The other half of the job

You can already build. The free ebook answers the rest: which business is right for you, the real numbers behind each path, and the ladder to climb without quitting your job.

join 2,700+ developers · unsubscribe anytime · no spam, only receipts

Include vs Extend in Ruby | Devmystify