class Rectangle
include Perimeter
def initialize(length, breadth) @length = length @breadth = breadth
end
def sides
[@length, @breadth, @length, @breadth]
end
end
class Square
include Perimeter
def initialize(side) @side = side
end
def sides
[@side, @side, @side, @side]
end
end
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 }
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