数组示例
arr = ["a", "b", "c"]
# TODO create an alias for arr[1] as x
x = "X"
# arr should be ["a", "X", "c"] here
哈希示例
hash = { :a => "aaa", :b => "bbb" , :c => "ccc" }
# TODO create an alias for hash[:b] as y
y = "YYY"
# hash should be { :a => "aaa", :b => "YYY" , :c => "ccc" } here
还有一个变量的别名?
var = 5
# TODO create an alias for var as z
z = 7
# var should be 7 here
动机:我有一个大而深的数据结构,其余的你可以想象。我想以只读方式使用它,但由于性能原因,不允许复制。
隐喻:我想从一个更大的数据结构中选择上下文,我想用一个简短的名字来访问它。
更新:问题已按照 sepp2k 的建议解决。我只想在这里画一个关于解决方案的总结图。
irb(main):001:0> arr = [ { "a" => 1, "b" => 2}, { "x" => 7, "y" => 8 } ]
=> [{"a"=>1, "b"=>2}, {"x"=>7, "y"=>8}]
irb(main):002:0> i = arr[0]
=> {"a"=>1, "b"=>2}
irb(main):004:0> j = arr[1]
=> {"x"=>7, "y"=>8}
irb(main):007:0> j["z"] = 9
=> 9
irb(main):008:0> j
=> {"x"=>7, "y"=>8, "z"=>9}
irb(main):009:0> arr
=> [{"a"=>1, "b"=>2}, {"x"=>7, "y"=>8, "z"=>9}]