Created
November 4, 2012 19:05
-
-
Save alandotcom/4013119 to your computer and use it in GitHub Desktop.
Internal state is not cloned
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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