Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR RUBY

ruby clone vs dup

class Klass
  attr_accessor :str
end

module Foo
  def foo; 'foo'; end
end

s1 = Klass.new #=> #<Klass:0x401b3a38>
s1.extend(Foo) #=> #<Klass:0x401b3a38>
s1.foo #=> "foo"

s2 = s1.clone #=> #<Klass:0x401b3a38>
s2.foo #=> "foo"

s3 = s1.dup #=> #<Klass:0x401b3a38>
s3.foo #=> NoMethodError: undefined method `foo' for #<Klass:0x401b3a38>

# While clone is used to duplicate an object, including its internal 
#state, dup typically uses the class of the descendant object to create 
#the new instance.
 
PREVIOUS NEXT
Tagged: #ruby #clone #dup
ADD COMMENT
Topic
Name
3+5 =