Skip to content

Instantly share code, notes, and snippets.

@Whoops
Created May 24, 2011 22:34
Show Gist options
  • Save Whoops/989910 to your computer and use it in GitHub Desktop.
Save Whoops/989910 to your computer and use it in GitHub Desktop.
Demonstration of shallow copy
require 'pp'
class DupMe
attr_accessor :stuff
def initialize
@stuff=[1,2,3,4,5,6]
end
def copy
new = self.dup
new.stuff=@stuff.dup
new
end
end
original = DupMe.new
dupped = original.dup
copied = original.copy
dupped.stuff.pop
pp original.stuff
pp dupped.stuff
pp copied.stuff
puts
dupped.stuff = "hello"
copied.stuff = "I'm a copy"
pp original.stuff
pp dupped.stuff
pp copied.stuff
require 'pp'
class DupMe
attr_accessor :stuff
def initialize
@stuff=[1,2,3,4,5,6]
end
def initialize_copy(source)
@stuff=stuff.dup
end
def copy
new = self.dup
new.stuff=@stuff.dup
new
end
end
original = DupMe.new
dupped = original.dup
copied = original.copy
dupped.stuff.pop
pp original.stuff
pp dupped.stuff
pp copied.stuff
puts
dupped.stuff = "hello"
copied.stuff = "I'm a copy"
pp original.stuff
pp dupped.stuff
pp copied.stuff
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment