Understanding passing by value vs. reference in this Ruby example
<p>After reading <a href="https://stackoverflow.com/questions/1872110/is-ruby-pass-by-reference-or-by-value">Is ruby pass by reference or value?</a> I have learned a lot, but I am left with more questions than I had before reading it (which I suppose is good).</p>

<p>Consider the following example </p>

<pre><code>def foo(bar) 
  bar = 'reference' 
end
baz = 'value' 
foo(baz)
puts "Ruby is pass-by-#{baz}"
</code></pre>

<p><strong>Output</strong>
<code>Ruby is pass-by-value</code></p>

<p><strong>Here is my attempt to dissect how this works:</strong></p>

<p>First, in the global scope <code>baz</code> has the value <code>value</code>.</p>

<p>Now <code>foo</code> takes a parameter, whatever you pass into it, is on a <code>local</code> level. </p>

<p>Therefore when we pass <code>baz</code> in, there is ANOTHER <code>baz</code> that is equal to <code>reference</code> but this is on the <strong>local level</strong>, as a result, when we puts this on a <strong>global</strong> level it prints <code>value</code>.</p>

<p><strong>Now consider another example</strong></p>

<pre><code>def foo(bar)
  bar.replace 'reference' 
end
baz = 'value'
foo(baz)
puts "Ruby is pass-by-#{baz}"
</code></pre>

<p><strong>Output</strong></p>

<p><code>Ruby is pass-by-reference</code></p>

<p>If what I said above is true, does the <code>.replace</code> method here change the global <code>baz</code>? 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.</p>

<p>Thanks!</p>

<p>EDIT</p>

<p><strong>More Magic</strong></p>

<pre><code>def my_foo(a_hash)
  a_hash["test"]="reference"
end;

hash = {"test"=&gt;"value"}
my_foo(hash)
puts "Ruby is pass-by-#{hash["test"]}"
</code></pre>