Friday, 25 July 2014

Difference between clone and dup

clone: Produces a shallow(as deep as possible) copy of obj.the instance variables of obj are copied, but not the objects they reference. Copies the frozen(cant be modified more) state of obj.

clone will copy the object alone with its internal state. suppose obj extends any module then clone of the obj also have that module extended.

example:
class Hello 
end

 module SayHello
 
  def sayhello
     'hello'
   end
 end


 s = Hello.new
 s.extend(SayHello)
 s1 = s.clone
 s1.sayhello                //     returns  "hello"


dup: Produces a shallow copy of obj.the instance variables of obj are copied, but not the objects they reference.

example:

use the above example if we use dup to create a copy of obj then dup will create a shallow copy of the obj excluding the internal state of the obj.

 s = Hello.new
 s.extend(SayHello)
 s1 = s.dup
 s1.sayhello             
 //     returns  undefined method `sayhello' for #<Hello:0x0000000197b688>















No comments:

Post a Comment