Ruby 中数组或散列元素的别名
数组的示例 散列的
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}]
Example for array
arr = ["a", "b", "c"]
# TODO create an alias for arr[1] as x
x = "X"
# arr should be ["a", "X", "c"] here
Example for hash
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
And also an alias for a variable?
var = 5
# TODO create an alias for var as z
z = 7
# var should be 7 here
Motivation: I have a big large deep construct of data, and you can imagine the rest. I want to use it in a read-only manner, but due to performance reasons copy is not permissible.
Metaphor: I want to choose context from a larger data structure and I want to access it with a short and simple name.
UPDATE: Problem solved as sepp2k advised. I just want to draw a summarizing picture here about the solution.
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}]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你想要的东西是不可能的。 ruby 中没有任何功能可以让您的示例按照您想要的方式工作。
但是,既然您说您只想以只读方式使用它,则没有必要这样做。您只需执行
x = myNestedStructure[foo][bar][baz]
即可。当您这样做时,不会涉及复制。赋值不会复制 ruby 中分配的对象。What you want is not possible. There is no feature in ruby that you could use to make your examples work like you want.
However since you're saying you want to only use it read-only, there is no need for that. You can just do
x = myNestedStructure[foo][bar][baz]
. There will be no copying involved when you do that. Assignment does not copy the assigned object in ruby.您必须创建一个作为别名的方法,它将更新数据。
然后调用它。
编辑:更新了第二个代码片段。
You would have to create a method that is your alias, which would update the data.
Then call it.
Edit: updated second code snippet.