From: Eric Mahurin Date: 2007-10-05T22:56:05+09:00 Subject: Re: Reference vs. Reference On 10/5/07, Rick DeNatale wrote: > > If you really wanted to get the semantics of call-by-reference in > > ruby, you'd have to do something like the following. > > > > def foo(get_bar, set_bar) > > get_bar[] # get the value of the bar reference : 123 > > set_bar[345] # set the value of the bar reference > > get_bar[] # 345 > > end > > > > bar = 123 > > foo(lambda {bar}, lambda {|v| bar=v}) > > > > Of course you could combine the getter/setter into one lambda (with an > > optional setting value) and/or wrap this into an object to make it > > look prettier. > > This is more like call-by-name with the lambda(s) acting as a thunk. For the getter you are correct, it is indeed deferred evaluation like call-by-name. But, in the above we also have the ability to assign to an lvalue, which call-by-name doesn't (normally) have. If the getter and setter respectively evaluate and assign the same lvalue expression, the semantics are the same as call-by-reference. How this is done is just an implementation detail. Here would be another way with just a single lambda: def foo(bar) bar[] # get the value of the bar reference : 123 bar[345] # set the value of the bar reference bar[] # 345 end bar = 123 foo(lambda { |*v| (v.empty?) ? bar : (bar = v[0]) } ) Something like this is the closest that ruby has to call-by-reference. Eric