Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference a value for a key in a hash

Tags:

ruby

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!

like image 803
axsuul Avatar asked Oct 23 '22 16:10

axsuul


1 Answers

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"}
like image 118
Andrew Marshall Avatar answered Oct 27 '22 10:10

Andrew Marshall