On 10/2/10, Josh Cheek <josh.cheek / gmail.com> wrote:
> On Sat, Oct 2, 2010 at 6:41 PM, Ralph Shnelvar <ralphs / dos32.com> wrote:
>
>> I see
>>  http://www.ruby-forum.com/topic/41160
>>
>> which has a fairly long explanation of passing stuff by reference and copy
>> on write(cow).
>>
>>
>> Let's say I have
>>  def som_func(x,y)
>>   x = 24
>>   y = 42
>>  end
>>  .
>>  .
>>
>>  a=1
>>  b=2
>>  .
>>  .
>>  .
>>  some_func(a,b)
>>
>>
>> and I want to have some_func change a to 24 and b to 42 ...
>>
>> How do I do it?
>>
>>
>> Is there a good write-up on copy on write and how to change the values of
>> parameters?

> You could get around this by writing a wrapper class to allow them to be
> mutable.
>
> class MutableValue
>   def initialize(initial_value)
>     @value = initial_value
>   end
>   def to_s
>     @value.to_s
>   end
>   def replace(new_value)
>     @value = new_value
>   end
>   def inspect
>     "#<Mutable #{to_s}>"
>   end
> end

Rather than inventing a new class to do pass-by-reference, I'd
advocate using one that already exists: Array. So then you could call
the method like this:

a = [1]
b = [2]
puts "initially: a=#{a[0]}, b=#{b[0]}"
change_value a , b
puts "after: a=#{a[0]}, b=#{b[0]}"

Now that I think about it, potentially Delegate could be used here as
well, and that might be a better choice.

Xavier Noria wrote:
> You can't. Ruby, C, and Java are pass-by-value. With that method call
> semantics what you ask is not possible. You certainly can change the
> state of a mutable object, but that is unrelated.
>
> Perl is pass-by-reference, you can do that in Perl.
>
> This is jargon, the word "reference" in "pass-by-reference" has
> nothing to do with the "references" that Java or Ruby manage. Same
> term, different meanings.

I disagree. The reference in the phrase 'pass by reference' is the
same thing as the references which  are stored in ruby variables. Ruby
is (mostly) a pass by reference language.

It's just that in the case of Fixnums (and a few other things) it is
not possible to have references at all; such objects are always stored
(and passed) by value and to support pass by reference in such cases
(or generally when objects are immutable) you must resort to trickery
such as using a Delegate, Array, or MutableValue to create an extra
level of referencing.