Note that there are some explanatory texts on larger screens.

plurals
  1. PODoes Ruby have a way to return a reference, similar to PHP?
    text
    copied!<p>In PHP I can use <code>&amp;</code> to assign the <code>reference</code> of a variable to another variable as seen in the first code snippet below.</p> <blockquote> <p>See PHP "Returning References" documentation for some more context... <a href="http://www.php.net/manual/en/language.references.return.php" rel="nofollow">http://www.php.net/manual/en/language.references.return.php</a></p> </blockquote> <p>PHP Code:</p> <pre><code>&lt;?php $tree = array(); $tree["branch"] = array(); $tree["branch"]["leaf"] = "green"; echo '$tree: '; var_dump($tree); $branch = &amp;$tree["branch"]; $branch = "total replacement!"; echo '$tree: '; var_dump($tree); ?&gt; </code></pre> <p>PHP's output:</p> <pre><code>$tree: array(1) { ["branch"]=&gt; array(1) { ["leaf"]=&gt; string(5) "green" } } $tree: array(1) { ["branch"]=&gt; &amp;string(18) "total replacement!" } </code></pre> <p>Trying to do this in Ruby I did:</p> <pre><code>tree = {} tree["branch"] = {} tree["branch"]["leaf"] = "green" puts "tree: #{tree.inspect}" branch = tree["branch"] branch = "total replacement!" puts "tree: #{tree.inspect}" </code></pre> <p>Which output:</p> <pre><code>tree: {"branch"=&gt;{"leaf"=&gt;"green"}} tree: {"branch"=&gt;{"leaf"=&gt;"green"}} </code></pre> <p>Now, while this straight assignment does not work in Ruby, modification of the object does:</p> <p>Ruby Code (Continued):</p> <pre><code>branch["lead"] = "red" puts "tree: #{tree.inspect}" </code></pre> <p>Ruby's Output:</p> <pre><code>tree: {"branch"=&gt;{"leaf"=&gt;"red"}} </code></pre> <p>So, I'm left wondering if there is a way to find the "parent" of an object so that I might modify it like I've done with <code>branch["leaf"]</code>.</p> <p><strong>Author Edit:</strong></p> <p>While one <strong>can't</strong> change a hash reference to any other variable through assignment (e.g., <code>x = y</code>), one <strong>can</strong> modify the existing object through its methods. Using this approach one can <em>pseudo-assign</em> a new <code>hash</code> to the <code>branch</code> variable using <code>.replace()</code> as seen below...</p> <p>Replacement Instead of Assignment:</p> <pre><code>tree = {} tree["branch"] = {} tree["branch"]["leaf"] = "green" puts "tree: #{tree.inspect}" branch = tree["branch"] branch.replace({"leaf" =&gt; "red", "twig" =&gt; "brown"}) puts "tree: #{tree.inspect}" </code></pre> <p>Output: </p> <pre><code>tree: {"branch"=&gt;{"leaf"=&gt;"green"}} tree: {"branch"=&gt;{"leaf"=&gt;"red", "twig"=&gt;"brown"}} </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload