In PHP I can use &
to assign the reference
of a variable to another variable as seen in the first code snippet below.
See PHP "Returning References" documentation for some more context... http://www.php.net/manual/en/language.references.return.php
PHP Code:
<?php
$tree = array();
$tree["branch"] = array();
$tree["branch"]["leaf"] = "green";
echo '$tree: ';
var_dump($tree);
$branch = &$tree["branch"];
$branch = "total replacement!";
echo '$tree: ';
var_dump($tree);
?>
PHP's output:
$tree: array(1) {
["branch"]=>
array(1) {
["leaf"]=>
string(5) "green"
}
}
$tree: array(1) {
["branch"]=>
&string(18) "total replacement!"
}
Trying to do this in Ruby I did:
tree = {}
tree["branch"] = {}
tree["branch"]["leaf"] = "green"
puts "tree: #{tree.inspect}"
branch = tree["branch"]
branch = "total replacement!"
puts "tree: #{tree.inspect}"
Which output:
tree: {"branch"=>{"leaf"=>"green"}}
tree: {"branch"=>{"leaf"=>"green"}}
Now, while this straight assignment does not work in Ruby, modification of the object does:
Ruby Code (Continued):
branch["lead"] = "red"
puts "tree: #{tree.inspect}"
Ruby's Output:
tree: {"branch"=>{"leaf"=>"red"}}
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 branch["leaf"]
.
Author Edit:
While one can't change a hash reference to any other variable through assignment (e.g., x = y
), one can modify the existing object through its methods. Using this approach one can pseudo-assign a new hash
to the branch
variable using .replace()
as seen below...
Replacement Instead of Assignment:
tree = {}
tree["branch"] = {}
tree["branch"]["leaf"] = "green"
puts "tree: #{tree.inspect}"
branch = tree["branch"]
branch.replace({"leaf" => "red", "twig" => "brown"})
puts "tree: #{tree.inspect}"
Output:
tree: {"branch"=>{"leaf"=>"green"}}
tree: {"branch"=>{"leaf"=>"red", "twig"=>"brown"}}