include Vs extend
Include Vs Extend
include:
- It is used for importing module code. Ruby will throw an error when we try to access the methods of import module with the class directly because it gets imported as a subclass of the superclass so the only way to access it is through the instance of the class.
extend:
- It is also used for importing modules. Ruby will throw an error when we try to access methods of import module with the instance of the class because the module gets imported to the superclass so the only way to access it is through the class definition
In simple words, include is for adding methods only to an instance of a class, and extend is for adding methods to the class. We can use extend and include in-class together also.
Example:
# include Vs extend
module Test
def show
p “Module Show”
end
endclass Lord
include Test
endclass Star
extend Test
endclass Disp
include Test
extend Test
endLord.new.show # “Module Show”
Lord.show # main.rb:16:in `<main>’: undefined method `show’ for Lord:Class (NoMethodError)Star.show # “Module Show”
Star.new.show # main.rb:19:in `<main>’: undefined method `show’ for #<Star:0x00559627d1e198> (NoMethodError)Disp.new.show # “Module Show”
Disp.show # “Module Show”