On Jun 21, 2014, at 5:31 AM, Roelof W. [email protected] wrote:

class Rectangle

now I can calculate the permiter when using the sides defenition of square and

rectangle

but how do I know which is the calling class.

So I can do something like this : class.sides.each { |sum, x| sum + x }

Roelof

Including the module in a class adds it to the ancestors of the class,

so when Ruby searches for methods on a Square or a Rectangle it will

search the module after searching the including class.

If you consider code like this:

s = Square.new(10)

puts s.perimeter

r = Rectangle.new(4, 5)

puts r.perimeter

then when you send perimeter to s or r self will be an instance of a

particular class, and that determines where to dispatch the sides

message to when calculating the perimiter.

You can try something like:

module Perimeter

def perimeter

puts “perimiter: operating on a #{self.class}”

sides.reduce {|sum, n| sum + n}

# That could be shortened to

# sides.reduce :+

end

end

and see what it does. For the sample above I see:

~/tmp ∙ ./try.rb

perimiter: operating on a Square

40

perimiter: operating on a Rectangle

18

Hope this helps,

Mike

–

Mike S. [email protected]

http://www.stok.ca/~mike/

The “`Stok’ disclaimers” apply.