Skip to content

Instantly share code, notes, and snippets.

@carlosantoniodasilva
Created May 13, 2012 20:58
Show Gist options
  • Save carlosantoniodasilva/2690175 to your computer and use it in GitHub Desktop.
Save carlosantoniodasilva/2690175 to your computer and use it in GitHub Desktop.
Ruby dup/clone behavior
class A
def initialize_dup(other)
puts 'init dup'
super
end
def initialize_clone(other)
puts 'init clone'
super
end
def initialize_copy(other)
puts 'init copy'
super
end
end
class B < A
def initialize_dup(other)
puts 'B init dup'
end
def initialize_clone(other)
puts 'B init clone'
end
def initialize_copy(other)
puts 'B init copy'
end
end
class C < A
def initialize_dup(other)
puts 'C init dup'
super
end
def initialize_clone(other)
puts 'C init clone'
super
end
def initialize_copy(other)
puts 'C init copy'
super
end
end
def debug(klass)
puts "#{klass.name} =="
puts 'dup'
klass.new.dup
puts 'clone'
klass.new.clone
puts '---'
end
debug A
debug B
debug C
=begin
### Output
$ ruby dup.rb
A ==
dup
init dup
init copy
clone
init clone
init copy
---
B ==
dup
B init dup
clone
B init clone
---
C ==
dup
C init dup
init dup
C init copy
init copy
clone
C init clone
init clone
C init copy
init copy
---
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment