Include is used to 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 for the superclass. So, the only way is to access it through the instance of the class. Extend is also used to importing module code but extends import them as class methods. Ruby will throw an error when we try to access methods of import module with the instance of the class because the module gets import to the superclass just as the instance of the extended module. So, the only way is to access it through the class definition. In simple words, the difference between include and extend is that ‘include’ is for adding methods only to an instance of a class and ‘extend’ is for adding methods to the class but not to its instance. Example :
Ruby
module Geek
def geeks
puts 'GeeksforGeeks!'
end
end
class Lord
include Geek
end
class Star
extend Geek
end
Lord. new .geeks
Star.geeks
Lord.geeks
|
Output
GeeksforGeeks!
GeeksforGeeks!
main.rb:20:in `': undefined method `geeks' for Lord:Class (NoMethodError)
If we want to import instance methods on a class and its class methods too. We can ‘include’ and ‘extend’ it at the same time. Example :
Ruby
module Geek
def prints(x)
puts x
end
end
class GFG
include Geek
extend Geek
end
GFG . new .prints("Howdy")
GFG .prints("GeeksforGeeks!!")
|
Output
Howdy
GeeksforGeeks!!