include and extend in ruby
Today I would like to explain differences between include and extend in Ruby.Include: Include it is adding methods of a class to an instance which we created.
Extend: Extend it is for adding class methods itself.
If we go with a simple example we can get a clear picture
module Advertisement
def advertisement
puts ‘upgrade to new rails version’
end
end
class Movie
include Advertisement
end
Movie.new.advertisement # upgrade to new rails version
Movie.advertisement # NoMethodError: undefined method ‘advertisement’ for
Movie:Class
class Game
extend Advertisement
end
Game.advertisement # upgrade to new rails version
Game.new.advertisement # NoMethodError: undefined method ‘advertisement’ for #<Game:0x1e708>
So that from above example we can get a basic idea that “include” makes the advertisement method available to an instance of a class
and where as the extend makes the advertisement method available to the class itself.