After reading Is ruby pass by reference or value? I have learned a lot, but I am left with more questions than I had before reading it (which I suppose is good).
Consider the following example
def foo(bar)
bar = 'reference'
end
baz = 'value'
foo(baz)
puts "Ruby is pass-by-#{baz}"
Output
Ruby is pass-by-value
Here is my attempt to dissect how this works:
First, in the global scope baz
has the value value
.
Now foo
takes a parameter, whatever you pass into it, is on a local
level.
Therefore when we pass baz
in, there is ANOTHER baz
that is equal to reference
but this is on the local level, as a result, when we puts this on a global level it prints value
.
Now consider another example
def foo(bar)
bar.replace 'reference'
end
baz = 'value'
foo(baz)
puts "Ruby is pass-by-#{baz}"
Output
Ruby is pass-by-reference
If what I said above is true, does the .replace
method here change the global baz
? Am I interpreting this correctly? Please feel free to point out any mistakes in my attempts, I have no clue if im on the right track.
Thanks!
EDIT
More Magic
def my_foo(a_hash)
a_hash["test"]="reference"
end;
hash = {"test"=>"value"}
my_foo(hash)
puts "Ruby is pass-by-#{hash["test"]}"