Forum: Ruby How do two objects communicate?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
E29eaefee1709918198c8a4f55c42667?d=identicon&s=25 anne (Guest)
on 2005-11-26 01:36
(Received via mailing list)
I wrote a small program the procedural way, now I would like to write
one the OOP way, but
I am blocking on the matter of communication.

One way to communicate is to have a class variable, ie a global to the
class.

So lets say I define a class with two class variables and a storage
array
class dataClass
     def initialize
        @@Arr=array read from file, constant
        @@ind=0
        @storeAr=[]
     end
end

I can create two objects (two instances)
datainst=dataClass.new
infoinst=dataClass.new

As I understand it the objects datainst and infoinst both have access
to @@Arr and @@ind,
and each have their own array.

I can get my program rolling by calling a method, say datainst.lookforX
class dataClass
    def lookforX
        look for X in @@arr[@@ind]
        if X not found
            increase @@ind
            Self.lookforX
        else X is found
            Send a message to other object   ?????  HOW DO I DO THAT?
            break out of all recursions
        end
    end
end

The object datainst can call itself with Self I believe but how does
object datainst tell infoinst
to do something? Methods are written in a class, and when one writes a
class, instances don't yet exist.

The examples in my programming ruby always seem to be "me" sending a
"message" to an object, not an object talking to another object? How
can an object talk to another object?
Ruby and OOP beginner missing something
Bc6d88907ce09158581fbb9b469a35a3?d=identicon&s=25 james_b (Guest)
on 2005-11-26 02:04
(Received via mailing list)
anne001 wrote:
...

> The examples in my programming ruby always seem to be "me" sending a
> "message" to an object, not an object talking to another object? How
> can an object talk to another object?
> Ruby and OOP beginner missing something

One way is to register one or more objects with another object, and have
those objects contacted on certain events.  Another approach is to
inspect the set of known objects and invoke a method based on some
criteria (basically, 'broadcast' to ObjectSpace).



class A
   def initialize( name )
      @name = name
   end
   def notify1
     puts "Where's breakfast?"
   end

   def notify2
     puts "Where's dinner?"
   end

   def feed_me
     puts "Feed #{@name}"
   end

end

class B

   def initialize
     @notify_these = {}
   end

   def register( obj, meth_name  )
      @notify_these[ obj ] = meth_name
   end

   def the_magic_event
     @notify_these.each do |obj, m|
       obj.send  m
     end
   end

   def yell_to_the_crowd
     ObjectSpace.each_object do |o|
       o.send( :feed_me ) if o.class == A
      end
   end
end


b= B.new

a1 = A.new( 'a1' )
a2 = A.new( 'a2' )
b.register( a1, :notify1 )
b.register( a2, :notify2 )

# Contact those who requested notification
b.the_magic_event

# Ignore the Do Not Call list:
b.yell_to_the_crowd



James


--

http://www.ruby-doc.org       - Ruby Help & Documentation
http://www.artima.com/rubycs/ - Ruby Code & Style: Writers wanted
http://www.rubystuff.com      - The Ruby Store for Ruby Stuff
http://www.jamesbritt.com     - Playing with Better Toys
http://www.30secondrule.com   - Building Better Tools
A083f2c63fc0be7f8f19006c9dbdff86?d=identicon&s=25 dale.martenson (Guest)
on 2005-11-27 01:18
(Received via mailing list)
Depending on the relationship between the classes, you may want to look
at Observable. Observable is commonly used when you wish to have one
class notify a number of observes of a change in the object being
observed.

http://www.ruby-doc.org/stdlib/

Look for information on 'observer'.

--Dale
E29eaefee1709918198c8a4f55c42667?d=identicon&s=25 anne (Guest)
on 2005-11-27 04:03
(Received via mailing list)
Thank you so much!

http://java.sun.com/docs/books/tutorial/java/concepts/
What Is an Object?
An object is a software bundle of related variables and methods.

What Is a Message?
Software objects interact and communicate with each other using
messages.

object communication through messages seems at the core of OOP, and yet
"observer" is not in my sams teach yourself ruby's index, it is only in
the reference section of programming ruby, 2nd edition. Same for send
which seems key to the example.

Why is something which is at the heart of OOP so little explained? I am
baffled.

Thank you so much for the example, and all this info

Anne
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 dblack (Guest)
on 2005-11-27 04:19
(Received via mailing list)
Hi --

On Sun, 27 Nov 2005, anne001 wrote:

> object communication through messages seems at the core of OOP, and yet
> "observer" is not in my sams teach yourself ruby's index, it is only in
> the reference section of programming ruby, 2nd edition. Same for send
> which seems key to the example.
>
> Why is something which is at the heart of OOP so little explained? I am
> baffled.

The Observable module is a rather specialized tool, and not at all at
the heart of Ruby's OO model.  The fact that Ruby is all about message
sending is manifested every time you see this:

   object.message

That's one object sending a message to another object.  I think you'll
find plenty of examples of that in "Teach Yourself Ruby" :-)


David
E29eaefee1709918198c8a4f55c42667?d=identicon&s=25 anne (Guest)
on 2005-11-27 13:29
(Received via mailing list)
Yes, I am aware of the structure.
object.message

In discussions of OOP I read, the difference is made between
procedural, which starts with data, and flows from action to action to
an end point in a structure organized by time, and OOP, portrayed as
objects linked together by actions in timeless fashion.

I think what I am discovering, is that for most of its communication,
OOP relies on a hierarchy all the same, but a hierarchy of objects. If
object A and object B need to communicate, they can as long as they are
embedded in object C which can call on A and on B as needed. Something
like that.

That seems to be what OOP demystified is explaining in its example on
collaboration in chapter 9. Because Keogth called the super class,
linkCourseStudent, I did not realize that it was creating a class in a
hierarchy which could create an instance of objects of class Course and
of class Student, and call each instance method, giving "the
appearance" of communication.

As James Britt showed me, it is possible for A and B to communicate
without being embeded in a common hierarchical object, but it is much
less commonly done.

Am I getting this right?
784481e009179262d133db1f1eb3bfb1?d=identicon&s=25 Edwin Van leeuwen (blackedder)
on 2005-11-27 13:39
anne wrote:
> Am I getting this right?
Partly, most objects communicate only with objects they create and the
object that created them.

class A
  def initialize
    arr=[1,2,3,4]
    arr.last
  end
  def ask
    return arr.first
  end
end

a=A.new
last=a.ask


Here the object we are currently in creates a object a of class A, it
communicates with this object with a.ask. The object a itself creates an
Object arr and also communicates with that. This is the way most object
communicate with each other.

If you need two object (A and B) that are created by a third object (C)
to communicate with each other then you are probably doing something
wrong (although not always) and it might have been better if Object A
had created object B instead of letting Object C create both.

Hope that clears some things up :)

Edwin
E29eaefee1709918198c8a4f55c42667?d=identicon&s=25 anne (Guest)
on 2005-11-27 14:09
(Received via mailing list)
Thank you Edwin van Leeuwen

OK, so it is even simpler than I thought, objects are usually organized
in a vertical hierarchy for communication. I will go back to the books
examples with this in mind and see how that works in practice.

thank you so much

Anne
5befe95e6648daec3dd5728cd36602d0?d=identicon&s=25 bob.news (Guest)
on 2005-11-27 15:06
(Received via mailing list)
anne001 <anne@wjh.harvard.edu> wrote:
> object A and object B need to communicate, they can as long as they
> are embedded in object C which can call on A and on B as needed.
> Something like that.

Not only: there's no need for C to be present.  A can reference B or
vice
versa ("containment").  So every method of the container has acceess to
the
contained instance and can send messages to (aka "invoke methods on")
that
instance.

If you view OO through the "hiearchy perspective" this is what
differenciates OO from procedural IMHO: procedural has only the
hierarchy of
procedure (or function) invocations.  OO does have this hiearchy of
method
invocations, too, but adds more, orthogonal hiearchies in different
areas:
at runtime there's the object composition hiearchy (on instance contains
or
references another which in turn contains or references other instances
etc. - in fact these can form arbitrary graphs not only strict
hiearchies).
Then there's the hierarchy of type relations called "class hiearchy".

> That seems to be what OOP demystified is explaining in its example on
> collaboration in chapter 9. Because Keogth called the super class,
> linkCourseStudent, I did not realize that it was creating a class in a
> hierarchy which could create an instance of objects of class Course
> and of class Student, and call each instance method, giving "the
> appearance" of communication.
>
> As James Britt showed me, it is possible for A and B to communicate
> without being embeded in a common hierarchical object, but it is much
> less commonly done.

IMHO the most common situation is actually where one instance references
another instance (in UML speak "aggregation" or "composition", see also
http://ootips.org/uml-hasa.html ).

One of the basic tasks of software engineering is to distribute
responsibilities properly over the code - whatever programming paradigm
(OO,
procedural, functional) is used.  For procedural languages this means to
identify the sub task that is delegated to another function / procedure
which can be invoked by several other functions / procedures.  For
example,
if in a procedural system you wanted to have a function that calculates
the
hypotenuse you would delegate square root calculation to another
function.

In OO environments it's a good rule of thumb to identify classes by
looking
at nouns.  If you had to model an application that deals with cars and
their
pieces you'd probably choose "car", "wheel", "engine", "lorry", "bus" as
classes, where some of the typically belong into an inheritance hiearchy
("car" probably as base class, "lorry", "bus") and others usually form a
containment hiearchy (a "car" has_an "engine" etc.).  If you managed to
identify classes then you often also know their methods ("start" for
"engine" etc.).  Of course it's not always that simple...

HTH

Kind regards

    robert
09b87770d7b50f3a7f913984477eea23?d=identicon&s=25 speechexpert (Guest)
on 2005-11-27 21:14
(Received via mailing list)
Anyone know how to do this?
I am curious to know what the solution is.
Thanks in advance,
John B
37a3c73ffbf864e4b28f7f2384ee12ce?d=identicon&s=25 Timothy Hunter (tim-hunter)
on 2005-11-27 21:18
(Received via mailing list)
speechexpert wrote:
> Anyone know how to do this?
> I am curious to know what the solution is.
> Thanks in advance,
> John B
>
>
Look up the pack method in Array.
09b87770d7b50f3a7f913984477eea23?d=identicon&s=25 speechexpert (Guest)
on 2005-11-28 02:49
(Received via mailing list)
Hi - Thanks for previous help, very useful.

At this point I have a problem:

I run Zlib (a compression class) on a string. It outputs a string of
bytes
(binary) Call it bout.  (bout = Zlib::Deflate.deflate(instr) )
I go bout.length It is 19994
Then I open a f = File.new(filename, "a")
I go f.write(bout)

At this point, the file is bigger than 19994.

What gives??

I know this is something simple, can anyone tell me what is going on?

(I tried "ab"  for the mode, but didn't help.)

Thanks in advance for any help!
John B
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 dblack (Guest)
on 2005-11-28 03:01
(Received via mailing list)
Hi --

On Mon, 28 Nov 2005, speechexpert wrote:

> At this point, the file is bigger than 19994.
>
> What gives??
>
> I know this is something simple, can anyone tell me what is going on?
>
> (I tried "ab"  for the mode, but didn't help.)

"a" is going to append, so maybe if you've run your program twice
you've actually written the data twice to the file.  "w" will
overwrite the file if it already exists, so you probably want that.


David
09b87770d7b50f3a7f913984477eea23?d=identicon&s=25 speechexpert (Guest)
on 2005-11-28 13:11
(Received via mailing list)
I did - but could see no way to pack a binary string.
Is there a way to pack a binary string of bytes?
jb

----- Original Message -----
From: "Timothy Hunter" <cyclists@nc.rr.com>
Newsgroups: comp.lang.ruby
To: "ruby-talk ML" <ruby-talk@ruby-lang.org>
Sent: Sunday, November 27, 2005 3:17 PM
Subject: Re: How to read/write an int in binary form to a file?
09b87770d7b50f3a7f913984477eea23?d=identicon&s=25 speechexpert (Guest)
on 2005-11-28 13:15
(Received via mailing list)
As far as appending, I erase the file every time to start again.
The problem is I n eed to pack the binary string and don't know how.
(yet)
JB

----- Original Message -----
From: "David A. Black" <dblack@wobblini.net>
To: "ruby-talk ML" <ruby-talk@ruby-lang.org>
Sent: Sunday, November 27, 2005 8:59 PM
Subject: Re: Case of the missing bytes
09b87770d7b50f3a7f913984477eea23?d=identicon&s=25 speechexpert (Guest)
on 2005-11-28 13:19
(Received via mailing list)
I need to write and then read a number of bytes to and from a file...
It seems the pack method will do it, but
does anyone know how to invoke it for a string of bytes?
Thanks in advance,
John B
37a3c73ffbf864e4b28f7f2384ee12ce?d=identicon&s=25 Timothy Hunter (tim-hunter)
on 2005-11-28 13:31
(Received via mailing list)
speechexpert wrote:
> I did - but could see no way to pack a binary string. Is there a way to
> pack a binary string of bytes?
> jb

I'm missing something, I think. You don't need to pack a binary string.
A binary string is already packed.
B5e329ffa0cc78efbfc7ae2d084c149f?d=identicon&s=25 dbalmain.ml (Guest)
on 2005-11-28 15:04
(Received via mailing list)
Don't know if this'll help;

f = File.new(filename, "ab")
6b4566518f6675477dab9b8ba813cf3c?d=identicon&s=25 ruby.brian (Guest)
on 2005-11-28 15:25
(Received via mailing list)
On 28/11/05, speechexpert <speechexpert@sbcglobal.net> wrote:
> I need to write and then read a number of bytes to and from a file...
> It seems the pack method will do it, but
> does anyone know how to invoke it for a string of bytes?
> Thanks in advance,
> John B
>
>
>

string = "some junk"

File.open('/tmp/junk', 'wb') do | file |
  file.print(string)
end

read = File.read('/tmp/junk')

p(string == read)

--
http://ruby.brian-schroeder.de/

Stringed instrument chords: http://chordlist.brian-schroeder.de/
09b87770d7b50f3a7f913984477eea23?d=identicon&s=25 speechexpert (Guest)
on 2005-11-28 15:37
(Received via mailing list)
yes - the "b" did it - I had 2 bugs going and didn't realize that fix
sooner.
Thanks to all,
John B

----- Original Message -----
From: "David Balmain" <dbalmain.ml@gmail.com>
To: "ruby-talk ML" <ruby-talk@ruby-lang.org>
Sent: Monday, November 28, 2005 9:00 AM
Subject: Re: Case of the missing bytes


Don't know if this'll help;

f = File.new(filename, "ab")
31ab75f7ddda241830659630746cdd3a?d=identicon&s=25 halostatue (Guest)
on 2005-11-28 18:27
(Received via mailing list)
On 11/28/05, speechexpert <speechexpert@sbcglobal.net> wrote:
> I did - but could see no way to pack a binary string.
> Is there a way to pack a binary string of bytes?

Can you post an example of what it is that you're trying to do?

-austin
Cb48ca5059faf7409a5ab3745a964696?d=identicon&s=25 ara.t.howard (Guest)
on 2005-11-28 18:43
(Received via mailing list)
On Mon, 28 Nov 2005, speechexpert wrote:

> I did - but could see no way to pack a binary string. Is there a way to pack
> a binary string of bytes?


   harp:~ > irb
   irb(main):001:0> byte_string = [0,0,0,42].map{|c| c.chr}.join
   => "\000\000\000*"

   irb(main):002:0> byte_string.size
   => 4

   irb(main):003:0> byte_string.unpack('N').first
   => 42


strings are already packed.  if you want to treat a string as a
collection of
bytes do

   harp:~ > irb
   irb(main):001:0> byte_string = [0,0,0,42].map{|c| c.chr}.join
   => "\000\000\000*"

   irb(main):002:0> bytes = byte_string.split(%r//).map{|b| b[0]}
   => [0, 0, 0, 42]

   irb(main):003:0> a = bytes.pack 'c*'
   => "\000\000\000*"

   irb(main):004:0> a.unpack('N').first
   => 42

hopefully you can figure out what to do from the above.

kind regards.

-a
This topic is locked and can not be replied to.