Skip to content

Instantly share code, notes, and snippets.

@alandotcom
Created November 4, 2012 19:05
Show Gist options
  • Select an option

  • Save alandotcom/4013119 to your computer and use it in GitHub Desktop.

Select an option

Save alandotcom/4013119 to your computer and use it in GitHub Desktop.
Internal state is not cloned
class Obj
attr_accessor :first, :second
def initialize
@first = {:one => 'x',:two => 'y',:three => 'z'}
@second = {[1,2]=>'x',[3,2]=>'o'}
end
end
# Using either dup or clone doesn't make a difference, they both make shallow copies
obj1 = Obj.new
obj2 = obj1.clone
# Different Objects in memory
obj1.object_id != obj2.object_id
# Internal state is identical. Pointing to same objects in memory
obj1.first.object_id == obj2.first.object_id
# Hack to make a deep copy -- copy the entire internal state
obj3 = Marshal.load( Marshal.dump(obj1) )
obj3.first.object_id != obj1.first.object_id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment