Wolfgang NĂ¡dasi-Donner <wonado / donnerweb.de> writes:

>>>>>> Code >>>>>
>
> def modifying(a_param)
>   a_param = "hi"
> end
>
> def modifying2(a_param=a_value)
>   a_param = "hi"
> end
>

In both the above cases, you are creating new objects that are only pointed to
by the variable a_param. Initially, that variable is referencing the same
object as the argument passed to the call. Effectively, you are chaging what is
being referenced. 


> def modifying3(a_param)
>   a_param[0..-1]= "hi"
> end

this one is different. You are changing the value of the object that the
argument references. You are not changing what is referenced. 

>
> a_value = "low"
> modifying a_value
> case a_value
> when "hi"
>   puts "Passed by reference"
> when "low"
>  puts "Passed by value"
> else
>  puts "Passed away"
> end
>
> a_value = "low"
> modifying2 a_value
> case a_value
> when "hi"
>   puts "Passed by reference"
> when "low"
>  puts "Passed by value"
> else
>  puts "Passed away"
> end
>
> a_value = "low"
> modifying3 a_value
> case a_value
> when "hi"
>   puts "Passed by reference"
> when "low"
>  puts "Passed by value"
> else
>  puts "Passed away"
> end
>
>>>>>> Output >>>>>
>
> Passed by value
> Passed by value
> Passed by reference
>
>>>>>> EoE >>>>>
>
> I would name it somehow "call by assignment of value to local variable",
> because the value of the actual parameter is assigned to the local variable
> used as a formal parameter.
>
> except for "Fixnum" etc. this is a pointer to an object. I one changes the
> object itself, it will work like  "by reference", otherwise only the local
> variable is affected, without having any effect to the outside world.
>

I don't think your example shows what you believe it is showing. However, to
some extent, this is because the pass by value and pass by reference is
irrelevant in a language like Ruby. What your example shows is the effect of
changing what a variable points to within a function compared to changing the
contents of what is pointed to, it doesn't really show differences in the
traditional pass by value/pass by reference sense. I would argue that in each
of the cases you have shown, the arguments are passed by value, but the value
being passed is a reference to an object. In the first two, you change that
reference, but as it was passed by value, it does not affect the callers
environment. In the third one, you are changing the object that is being
referenced and therefore the change is also visible to the calling environment.
However, the actual arguments were all passed by value.

Tim

-- 
tcross (at) rapttech dot com dot au