I want to be able to reference to a key in a Hash so that if the value for that key changes, so does anything referencing to it like so
hash = {}
hash[1] = "foo"
hash[2] = hash[1]
hash[1] = "bar"
puts hash[2] # I want this to be "bar"
Is this possible? Thanks!
It’s not possible. Here’s what’s happening:
Note that assigning
hash[1]does not change the object it refers to, but rather simply changes the object it references.In Ruby (like many higher-level languages) you do not have pointers and have no explicit ability to manipulate references.
However, there are some methods that are mutable, on String one such example is
upcase!. In this example we can see that this method modifies the actual object being referenced without assigning a new object (and thus the references remain unchanged):