1

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}]

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

You would have to create a method that is your alias, which would update the data.

def y=(value)
  arr[:b]=value
end

Then call it.

self.y="foo"

Edit: updated second code snippet.

2 Comments

No, you can't. You can call it with self.y = "foo", but not with y = "foo". y = "foo" will always assign to the local variable y, no matter what setter methods are defined.
2nd snippet needs to be self.y = foo, or else the local variable y is assigned, even when the method y is in scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.