Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

include vs. extend and Comparable module in Ruby

Looking for an explanation of an interesting Ruby observation. Consider mixing in the Comparable module as follows:

class Class0
end
class Class1
  include Comparable
end
class Class2
  extend Comparable
end

If we look for the methods which are in Class2 vs. Class0,

Class2.methods.each { |x| p x if not Class0.methods.include? x }

we get just :between?

But then, if we do this, to look for the difference between instances of Class1 and Class0,

a = Class0.new
b = Class1.new
b.methods.each { |x| p x if not a.methods.include? x }

we get

[:>, :>=, :<, :<=, :between?]

I would like to understand why the results are different. I would have expected the "extend" to push the same methods into the class that the "include" pushes into an instance. Are things like ":>" not methods in the same sense as ":between?" ??

like image 691
sploiber Avatar asked Jun 26 '26 05:06

sploiber


1 Answers

Include is for adding methods to an instance of a class and extend is for adding class methods: http://www.railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/

Both :> and :between are methods. The difference is here:

If you see Class0 methods you have :>, :>=, :<, :<= defined as class methods. When Class2 extend Comparable it will get the between? method as class method.

In the second case you have Class0 and Class1 instances, so the a instance of Class0 doesn't have the :>, :>=, :<, :<=, :between? methods defined as instance methods. Once you include the comparable Module in Class1, it will get all this methods as instance methods from Module, so you will have all [:>, :>=, :<, :<=, :between?] methods available in the instance b.

This is why you get those results.

I found another nice explanation of include VS extend here: http://aaronlasseigne.com/2012/01/17/explaining-include-and-extend/

like image 133
tbem Avatar answered Jun 29 '26 02:06

tbem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!