[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: object reference handle (like perl's reference to scalar

Eric Mahurin

5/6/2005 8:02:00 PM

I tried this out and it doesn't seem to do anything. I did a
require "delegate" followed by the code below. Could you give
a concrete example - working on mutable (string or array) and
immediate obects (i.e. Fixnum). Even if you get this to work
on the mutable objects, I don't see it working on the immediate
objects.

> --- dave.burt@gmail.com wrote:
> > To me, this looks more Rubyish. Is there some benefit I'm
> > missing in
> > your pulling variable names out of the closure like you do
> > there, Eric?
> > If it's all the same, why not just have the object pass
> > itself into a
> > reference constructor (as my Object#ref does)?
> > # ref.rb
> > #
> > # For those times you need an extra level of indirection.
> > #
> > # Example:
> > # def swap(a,b)
> > # tmp = a[]
> > # a[] = b[]
> > # b[] = tmp
> > # end
> > #
> > # swap(x.ref, y.ref) # convert x and y to references then
> > swap them
> > #
> > Ref = DelegateClass(Object) unless Object.const_defined?
> :Ref
> > class Ref
> > # Dereference (get the referred-to value)
> > alias deref __getobj__
> > # Call with no index to dereference
> > def [](*args)
> > if args.empty?
> > __getobj__
> > else
> > super
> > end
> > end
> > # Set value (change the reference to point at something
> > else)
> > def ref=(val) __setobj__(val) end
> > # Call with no index to assign a new value
> > def []=(*args)
> > if args.size == 1
> > __setobj__(args[0])
> > else
> > super
> > end
> > end
> > end
> > class Object
> > # Make a reference
> > def ref
> > Ref.new(self)
> > end
> > end




__________________________________
Yahoo! Mail Mobile
Take Yahoo! Mail with you! Check email on your mobile phone.
http://mobile.yahoo.com/...


1 Answer

Dave Burt

5/7/2005 3:35:00 AM

0

"Eric Mahurin" <eric_mahurin@yahoo.com> queried:

>> (ref.rb)

>I tried this out and it doesn't seem to do anything. I did a
> require "delegate" followed by the code below. Could you give
> a concrete example - working on mutable (string or array) and
> immediate obects (i.e. Fixnum). Even if you get this to work
> on the mutable objects, I don't see it working on the immediate
> objects.


# require 'ref'

irb(main):030:0> a = 1.ref
=> 1
irb(main):031:0> a.ref = 2 # []= is a synonym for ref=
=> 2
irb(main):032:0> a # here you can see the ref delegates inspect to the
number 2
=> 2
irb(main):033:0> a + 1 # and + is delegated too
=> 3
irb(main):034:0> a.class # class, kind_of?, is_a? and respond_to? aren't
=> Ref
irb(main):035:0> a.deref.class # [] is a synonym for deref
=> Fixnum

Maybe ref= should be called deref=. But there it is.

Cheers,
Dave