include and extend in ruby

include-and-extend-in-ruby_516bbf20eeb39

 

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s