On Wed, Jul 31, 2002 at 10:58:50PM +0900, Bill Tj wrote:
> Hi,
> 
> Is there any easy way to emulate C pointer or C++ reference in Ruby?

There is no need to emulate references.  With the exception of certain
primitive types (Fixnum, TrueClass, FalseClass, NilClass), all objects
are passed by reference in Ruby.

> Basically, the problem is something like this.  I have a root object,
> and it contains an instance variable that refers to, say, a file. 
> When the root object is created, it opens the file.  Then the root
> object creates many other child objects, passing the value of the file
> variable in the process.  Any child object will write to the same
> file.
> 
> Now, in the middle of execution, the root object may close the file,
> and some other program may access the file.  When the root object
> reopens the file, all the file variables in the child objects are no
> longer valid.  Therefore, I think it will be nice if the we can have
> some "reference" or "pointer", so that the child objects' file
> variables always point to the root object file variable.

Are you reopening your file with:
  @file.close
  @file = File.open("newfile")

or with:
  @file.reopen("newfile")

the former creates a new object; the latter re-uses the original object.

> The only solution that I can think of for now is for the root object
> to remember all the child objects, and to modify all the child
> objects' file variables whenever the root object file variable
> changes.  However, to me this is more like design pattern than a
> language feature.  (I read somewhere that in general the issue with
> programming languages is not whether something is possible, but rather
> whether the thing is facilitated.)

Some other options:
  1) Use a delegator.  A SimpleDelegator can change the object it is
     delegating to on-the-fly.  The children get a reference to the
     delegator instead of to the IO object you are using.
  2) Use the observer pattern.  Whenever you change which file you are
     accessing, mark your state as changed and notify your observers
     that they need to refetch their references.
  3) Use ts's suggestion of always accessing the file object via an
     accessor in the root object.

Paul