在 PHP 中,我可以使用&
将reference
一个变量的 分配给另一个变量,如下面的第一个代码片段所示。
有关更多上下文,请参阅 PHP“返回参考”文档... http://www.php.net/manual/en/language.references.return.php
PHP代码:
<?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的输出:
$tree: array(1) {
["branch"]=>
array(1) {
["leaf"]=>
string(5) "green"
}
}
$tree: array(1) {
["branch"]=>
&string(18) "total replacement!"
}
尝试在 Ruby 中执行此操作,我做到了:
tree = {}
tree["branch"] = {}
tree["branch"]["leaf"] = "green"
puts "tree: #{tree.inspect}"
branch = tree["branch"]
branch = "total replacement!"
puts "tree: #{tree.inspect}"
哪个输出:
tree: {"branch"=>{"leaf"=>"green"}}
tree: {"branch"=>{"leaf"=>"green"}}
现在,虽然这种直接赋值在 Ruby 中不起作用,但修改对象可以:
Ruby 代码(续):
branch["lead"] = "red"
puts "tree: #{tree.inspect}"
红宝石的输出:
tree: {"branch"=>{"leaf"=>"red"}}
所以,我想知道是否有办法找到一个对象的“父”,这样我就可以像修改它一样修改它branch["leaf"]
。
作者编辑:
虽然不能通过x = y
赋值(例如)更改对任何其他变量的散列引用,但可以通过其方法修改现有对象。使用这种方法,可以使用如下所示将新变量伪分配给hash
变量...branch
.replace()
替换而不是分配:
tree = {}
tree["branch"] = {}
tree["branch"]["leaf"] = "green"
puts "tree: #{tree.inspect}"
branch = tree["branch"]
branch.replace({"leaf" => "red", "twig" => "brown"})
puts "tree: #{tree.inspect}"
输出:
tree: {"branch"=>{"leaf"=>"green"}}
tree: {"branch"=>{"leaf"=>"red", "twig"=>"brown"}}