What is the differnece between extend and include in ruby?

Technology CommunityCategory: RubyWhat is the differnece between extend and include in ruby?
VietMX Staff asked 3 years ago
  • include mixes in specified module methods as instance methods in the target class
  • extend mixes in specified module methods as class methods in the target class

Given the following class definitions:

module ReusableModule
  def module_method
    puts "Module Method: Hi there! I'm a module method"
  end
end

class ClassThatIncludes
  include ReusableModule
end
class ClassThatExtends
  extend ReusableModule
end

Here’s how ClassThatIncludes behaves:

# A class method does not exist
>> ClassThatIncludes.module_method
NoMethodError: undefined method `module_method' for ClassThatIncludes:Class

# A valid instance method exists
>> ClassThatIncludes.new.module_method
Module Method: Hi there! I'm a module method
=> nil

Here’s how ClassThatExtends behaves:

# A valid class method exists
>> ClassThatExtends.module_method
Module Method: Hi there! I'm a module method
=> nil

# An instance method does not exist
ClassThatExtends.new.module_method
NoMethodError: undefined method `module_method' for #<ClassThatExtends:0x007ffa1e0317e8>

We should mention that object.extend ExampleModule makes ExampleModule methods available as singleton methods in the object.