From: Jim Weirich Date: 2001-12-07T12:51:20+09:00 Subject: [ruby-talk:27781] Re: References On Fri, Dec 07, 2001 at 09:14:18AM +0900, Phil Tomson wrote: > In article , > Mathieu Bouchard wrote: [... stuff about object references and non-reference objects and the effect on writing swap-like methods ... elided ...] > I think I understand why things are done this way (keeping references to > all of the numbers could prove unwieldly) .... but it does lead to some > inconsistencies in the way those four types are handled vs all others. > Should there be some mechanism to force pass-by-reference for these four > types (would it even be doable)? It wouldn't help. Even though objects are passed by reference, it is only a reference to the object, not a reference to the original variable in the calling program. You can't write swap(x,y) and have the values of x and y change (unless you resort to something like the eval in context technique). Here's a version of references I did a while ago where the context stuff is wrapped in a class. It does suffer from the assumption that interpolating "#{new_value}" in a string results in something reasonable. Sigh. class Ref def initialize(&block) @context = block @id = @context.call end def value eval("#{@id}", @context) end def value=(new_value) eval(@context) {"#{@id} = #{new_value}", @context) end end def swap(x,y) x.value, y.value = y.value, x.value end if __FILE__ == $0 then a = 1 b = 2 swap(Ref.new{:a}, Ref.new{:b}) puts "a=#{a}, b=#{b}" #=> a=2, b=1 end -- -- Jim Weirich jweirich@one.net http://w3.one.net/~jweirich --------------------------------------------------------------------- "Beware of bugs in the above code; I have only proved it correct, not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)