Skip to content

Instantly share code, notes, and snippets.

@acook
Last active December 26, 2015 02:19
Show Gist options
  • Save acook/7077174 to your computer and use it in GitHub Desktop.
Save acook/7077174 to your computer and use it in GitHub Desktop.
my_dict = { foo: 1, bar: 'baz' }
my_clone = my_dict.dup #=> making a shallow copy
my_clone.object_id == my_dict.object_id #=> false, these are different objects
my_clone == my_dict #=> true, they contain the same values
my_clone[:qux] = 'wibble' #=> adding a pair to the clone
my_clone.has_key? :qux #=> true, the key was added
my_dict.has_key? :qux #=> false, the key was never added to this object, neither was its value
my_clone[:bar].object_id == my_dict[:bar].object_id #=> true, because they reference the same string object
my_clone[:bar].gsub! 'z', 'ss' #=> mutating the string
my_dict[:bar] #=> 'bass', the string has been altered since they both reference the same object
my_clone[:foo] = 2 #=> changing a reference
my_clone[:foo] #=> 2, the reference now points to 2
my_dict[:foo] #=> 1, the reference remains where it was originally, since it was never changed
# documentation for dup: http://apidock.com/ruby/Object/dup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment