Skip to content

Instantly share code, notes, and snippets.

@Mon-Ouie
Created April 13, 2012 19:48
Show Gist options
  • Save Mon-Ouie/2379602 to your computer and use it in GitHub Desktop.
Save Mon-Ouie/2379602 to your computer and use it in GitHub Desktop.
class ShallowCopy
def initialize
@var = [1, 2, 3]
end
attr_reader :var
end
obj = ShallowCopy.new
cpy = obj.dup
puts cpy.var.equal? obj.var # => true, i.e. modifying @var in cpy affects obj
class DeepCopy
def initialize
@var = [1, 2, 3]
end
def initialize_copy(other)
@var = other.var.dup
end
attr_reader :var
end
obj = DeepCopy.new
cpy = obj.dup
puts cpy.var.equal? obj.var # => false, i.e. modifying @var in cpy doesn't
# afffect obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment