Last active
December 11, 2015 10:18
-
-
Save arnab/4585462 to your computer and use it in GitHub Desktop.
Ruby `dup` vs. `clone`. For http://www.arnab-deka.com/posts/2009/07/ruby-dup-vs-clone/
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
| the_clone = p.clone | |
| the_dup = p.dup |
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
| irb(main):018:0> the_clone.name | |
| => "The Man" | |
| irb(main):019:0> the_dup.name | |
| => "The Man" | |
| irb(main):020:0> the_clone.say_hi | |
| => "'sup" | |
| irb(main):021:0> the_dup.say_hi | |
| NoMethodError: undefined method `say_hi' for | |
| (Person :0xb7e83340 @name="The Man") | |
| from (irb):21 | |
| from :0 | |
| irb(main):022:0> |
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 Person | |
| attr_accessor :name | |
| end |
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
| p = Person.new | |
| p.name = "The Man" | |
| # now add a singleton method on p: | |
| def p.say_hi | |
| "'sup" | |
| end |
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
| irb(main):014:0> puts p.inspect | |
| #<person :0xb7e83340 @name="The Man"> | |
| => nil | |
| irb(main):015:0> puts p.say_hi | |
| 'sup | |
| => nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment