Ruby Details: clone and dup

Another post that’s mostly a reminder to self. 😉

Over at Know Ruby: clone and dup Aaron Lasseigne explained the differences between dup and clone.

However there’s another difference, and that’s the way the methods reproduce the methods an object can respond to. As is so often the case, a short session in a Ruby REPL (like irb or pry) helps to see things in action:

[1] pry(main)> o = Object.new
=> #<Object:0x00000102d298a0>
[2] pry(main)> def o.meth
[2] pry(main)* puts "meth called on object #{self.inspect}"
[2] pry(main)* end
=> :meth
[3] pry(main)> o.meth
meth called on object #<Object:0x00000102d298a0>
=> nil
[4] pry(main)> o_dupped = o.dup
=> #<Object:0x00000102101eb0>
[5] pry(main)> o_dupped.meth
NoMethodError: undefined method `meth' for #
from (pry):7:in `__pry__'
[6] pry(main)> o_cloned = o.clone
=> #<Object:0x00000102138168>
[7] pry(main)> o_cloned.meth
meth called on object #<Object:0x00000102138168>
=> nil

Note that both, clone and dup, return a new object, but only the one returned by clone also has the method defined for object o.
In other words: dup does not replicate an objects singleton methods.

Advertisement