Friday, 16 August 2013

What is the difference between include and extend in Ruby?

Okay  !!!!
Now let me describe the difference between include and extend in Ruby. This question is quite similar to my previous blog topic.

Include: When you Include a module into your class, it’s as if you took the code defined within the module and inserted it within the class, where you ‘include’ it. It allows the ‘mixin’ behavior. It’s used to DRY up your code to avoid duplication, for instance, if there were multiple classes that would need the same code within the module.
The following assumes that the module Log and class TestClass are defined in the same .rb file. If they were in separate files, then ‘load’ or ‘require’ must be used to let the class know about the module you’ve defined.

Extend: When using the extend method instead of include, you are adding the module’s methods as class methods instead of as instance methods. When using extend instead of include within the class, if you try to instantiate TestClass and call method class_type on it, as you did in the Include example above, you’ll get a NoMethodError. So, again, the module’s methods become available as class methods.

Thank you :)
keep visiting.
Post a Comment