[Courses] [Ruby] Lesson 1: Classes

Anne G anne at wjh.harvard.edu
Fri Dec 2 00:29:17 EST 2005


Thank you so much Laurel for your response. I will review
classes, and do the reading on lesson2 as you suggested.

First of all your suggestion expended my thinking to include
passing of an object. Thank you so much.

datainst.lookforX(infoinst)

I took this idea and tried to generalize it to 3 objects:

object1 -- stores data,  calls on object2 -- stores first
type of info, calls on object3 -- stores 2nd type of info,
calls back on object1.

I found myself doing the following:

storeobject.lookforX(info1object,info2object,storeobject)

this way lookforX knows to call on info1object
info1object knows to call on info2object
info2object knows to call on storeobject
...

I love this solution because it is totally within the scope
of what I can do. but it is a bit heavy and still smacks of
procedural in that I have to figure out what the whole chain
of objects will be instead of just relation between
pairs of objects.

Is this the way your suggestion would work with 3 objects?

---------------------------------------------------------

I found this recent discussion
http://groups.google.com/group/comp.lang.ruby/browse_frm/thread/68acf0f7c8a95138/1bbd14c18a57a45b#1bbd14c18a57a45b

Daniel Schierbeck offered a structure which seems simple
enough, and probably similar to yours, but it is a bit
confusing to my beginner's eye. What is hapening?

Here is what he said

Say you have three classes, A, B, and C, and you want their
instances to be able to communicate. These three classes
will all be instantiated together, so we know that the other
objects are there. You then write a class, let's just call
it Base, that you instantiate instead of the three classes.
It will instantiate them instead, and pass a reference to
itself to each of them.

   class Base
     attr_reader :a, :b, :c

     def initialize
       @a, @b, @c = A.new(self), B.new(self), C.new(self)
     end

     # We'll keep the other classes in here, so we don't
     # pollute the main namespace
     class A
       def initialize(base)
         @base = base
         @b, @c = base.b, base.c
       end
     end

     class B
       def initialize(base)
         @base = base
         @a, @c = base.a, base.c
       end
     end

     class C
       def initialize(base)
         @base = base
         @a, @b = base.a, base.b
       end
     end
   end

How would I use this in my expended task:
objectA needing to call on objectB needing to call on
objectC needing to call back on objectA

Thank you so much for running this course.

anne





More information about the Courses mailing list