 # How can I make the difference between the two classes

Hello,

I have this :

module Perimeter
def perimeter

end
end

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 }

Roelof

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

The “`Stok’ disclaimers” apply.

Mike S. schreef op 21-6-2014 13:16:

end
end
end

module Perimeter
~/tmp ??? ./try.rb
perimiter: operating on a Square
40
perimiter: operating on a Rectangle
18

Hope this helps,

Mike

Thanks,

Roelof

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs