How do two objects communicate?

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

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
Ruby Code & Style - 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

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

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

Hi --

Thank you so much!

Lesson: Object-Oriented Programming Concepts (The Java™ Tutorials > Learning the Java Language)
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.

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" :slight_smile:

David

···

On Sun, 27 Nov 2005, anne001 wrote:

--
David A. Black
dblack@wobblini.net

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?

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 :slight_smile:

Edwin

···

--
Posted via http://www.ruby-forum.com/\.

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.

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 (ootips) Association, Aggregation and Composition ).

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

···

anne001 <anne@wjh.harvard.edu> wrote:

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

Anyone know how to do this?
I am curious to know what the solution is.
Thanks in advance,
John B

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.

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

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?

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.

Hi --

···

On Mon, 28 Nov 2005, speechexpert wrote:

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.)

"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

--
David A. Black
dblack@wobblini.net

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

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.

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

-austin

···

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?

--
Austin Ziegler * halostatue@gmail.com
               * Alternate: austin@halostatue.ca

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

···

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?

--

ara [dot] t [dot] howard [at] noaa [dot] gov
all happiness comes from the desire for others to be happy. all misery
comes from the desire for oneself to be happy.
-- bodhicaryavatara

===============================================================================

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

Hi --

On Mon, 28 Nov 2005, speechexpert wrote:

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.)

"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

--
David A. Black
dblack@wobblini.net

string = "some junk"

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

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

p(string == read)

···

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

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

Stringed instrument chords: http://chordlist.brian-schroeder.de/