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:
hash[1] = "foo" # hash[1] is now a reference to the object "foo".
hash[2] = hash[1] # hash[2] is now a reference to the object "foo" as well,
# since it is what hash[1] is a reference to.
hash[1] = "bar" # hash[1] is now a reference to the object "bar"
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):
hash[1] = "foo" #=> "foo"
hash[2] = hash[1] #=> "foo"
hash[2].upcase! #=> "FOO"
hash # => {1=>"FOO", 2=>"FOO"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With