From: Eric Mahurin Date: 2007-10-05T13:10:36+09:00 Subject: Re: Reference vs. Reference On 10/4/07, Paul Brannan wrote: > > Ruby's evaluation strategy is actually "call by reference" although > > the description at > > http://en.wikipedia.org/wiki/Call_by_reference#Call_by_reference does > > not cover Ruby properly - unless you interpret "temporary object" as > > "copy of a reference" because this is how it works. > > This description sounds very C++-centric to me. In particular, I've > never heard Lvalue used as part of the definition of call-by-reference > (the discussion page seems to back me up on this a little). I think > foldoc's definition is better: > > http://foldoc.org/?call-by-reference > ... > Also note that the C2 wiki gives a third definition of > call-by-reference: > > http://c2.com/cgi/wiki?CallByReference The common theme with all of the above links is that the caller gives some kind of reference to an lvalue (i.e. variable) either implicitly or explicitly (i.e. C &) and the function may dereference implicitly or explicitly (i.e. C *) the corresponding argument to get or set the lvalue. There are a whole slew of languages that pass arguments like ruby. Most seem to call it call-by-value where the value is an object handle/pointer/reference. Python guys call it call-by-object-reference. I like what is said on c2.com: "Perhaps it's C/C++ background sneaking through... in a language with value semantics such as C/C++, pointers are how you do CallByReference. In languages with reference semantics (most OO languages, Java for objects but not for intrinsics), one could argue that the "handle" to the object is the value (and passing the handle is CallByValue); performing a second indirection and passing a reference to the handle (in C/C++ terminology, a Foo **) is how you do CallByReference. In which case, many OO languages do not allow CallByReference; using this definition (in Java) all calls are by value." Like Java, Ruby does have the equivalent of "intrinsics". They are the immediates (Fixnum, TrueClass, FalseClass, NilClass, and Symbol) which when used behave like the more conventional call-by-value. 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. Eric