Wednesday, March 25, 2015

Difference between "include" and "extend" in Ruby?

extend: 
If you're using a module, that means you're bringing all the methods into your class. If you extend a class with a module, that means you're "bringing in" the module's methods as class methods.

include:
If you include a class with a module, that means you're "bringing in" the module's methods as instance methods.

EX:


 module A
   def say
     puts "this is module A"
   end
 end

 class B
   include A
 end

 class C
   extend A
 end

Output:

 B.say
 => undefined method 'say' for B:Class



 B.new.say
 => this is module A



 C.say
 => this is module A



 C.new.say
 => undefined method 'say' for C:Class

1 comment:

  1. Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking.Ruby on Rails Online Training Hyderabad

    ReplyDelete