Forum: Ruby How can I make the difference between the two classes

39d8572ef267bc6771f1ef52527a9784?d=identicon&s=25 Roelof Wobben (Guest)
on 2014-06-21 11:32
(Received via mailing list)
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
2ffac40f8a985a2b2749244b8a1c4161?d=identicon&s=25 Mike Stok (Guest)
on 2014-06-21 13:17
(Received via mailing list)
On Jun 21, 2014, at 5:31 AM, Roelof Wobben <r.wobben@home.nl> 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 Stok <mike@stok.ca>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.
39d8572ef267bc6771f1ef52527a9784?d=identicon&s=25 Roelof Wobben (Guest)
on 2014-06-21 16:03
(Received via mailing list)
Mike Stok 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
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.