Skip to content

Instantly share code, notes, and snippets.

@vasilakisfil
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vasilakisfil/3a673fa53127a801e571 to your computer and use it in GitHub Desktop.
Save vasilakisfil/3a673fa53127a801e571 to your computer and use it in GitHub Desktop.
Ruby hashes inconsistency
# copy and store in another variable:
[16] pry(main)> hash1 = {a: 'asdasd', b: 'asdasd'}
=> {:a=>"asdasd", :b=>"asdasd"}
[17] pry(main)> hash2 = hash1
=> {:a=>"asdasd", :b=>"asdasd"}
[18] pry(main)> hash2.delete(:a)
=> "asdasd"
[19] pry(main)> hash2
=> {:b=>"asdasd"}
[20] pry(main)> hash1
=> {:b=>"asdasd"}
[21] pry(main)>
#shallow copy
[23] pry(main)> hash3 = {a: 'asdasd', b: 'asdasd'}
=> {:a=>"asdasd", :b=>"asdasd"}
[24] pry(main)> hash4 = hash3.clone
=> {:a=>"asdasd", :b=>"asdasd"}
[25] pry(main)> hash3.delete(:a)
=> "asdasd"
[26] pry(main)> hash3
=> {:b=>"asdasd"}
[27] pry(main)> hash4
=> {:a=>"asdasd", :b=>"asdasd"}
[28] pry(main)> hash3[:b] << ' something else'
=> "asdasd something else"
[29] pry(main)> hash3
=> {:b=>"asdasd something else"}
[30] pry(main)> hash4
=> {:a=>"asdasd", :b=>"asdasd something else"}
[31] pry(main)>
@vasilakisfil
Copy link
Author

here we see Ruby failing in multiple ways

  1. delete method deletes a hash element but actually changes the hash itself. It should be delete! instead.
  2. by setting the hash contents of a variable to another variable you actually have another reference to the same contents. So changing the contents of the new variable, you change the contents of the old variable too since both reference to the same address.
  3. even with clone method, ruby does a shallow copy so even (2) is solved, if you change the contents of the initial variable, contents of the cloned variable will be changed. It means that although the "hash's references are being copied, but not the objects that the references refer to".
  4. So you need a deep clone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment