clone and dup

K

Keith P. Boruff

After reading about these two methods for the Object class in "Pragmatic
Programmer", I'm still having a hard time understanding the differences.
Can someone point me to some better info on these or explain it (I do
understand the differences between deep and shallow copying).

Also, in some of the std modules I've peeked at like Find for instance, this
is called for the args:

def find(*paths)
paths.collect! { |d| d.dup }
...
end

Why would one dup the args in place? I definitely don't understand this.

Thanks,
KPB
 
R

Robert Klemme

Keith P. Boruff said:
After reading about these two methods for the Object class in "Pragmatic
Programmer", I'm still having a hard time understanding the differences.
Can someone point me to some better info on these or explain it (I do
understand the differences between deep and shallow copying).

They do both shallow copy.

Here's a difference:
=> false
Also, in some of the std modules I've peeked at like Find for instance, this
is called for the args:

def find(*paths)
paths.collect! { |d| d.dup }
...
end

Why would one dup the args in place? I definitely don't understand this.

Probably because the path names are modified later on and the implementer
of find wanted to avoide side effects on the arguments. Or he wanted to
make sure that modifications to the argument objects don't affect find()
as it is likely to run comparatively long compared to other methods.

Kind regards

robert
 
C

Csaba Henk

They do both shallow copy.

Here's a difference:

=> false

Or:

irb(main):189:0> o=Object.new
=> #<Object:0x414c1f54>
irb(main):190:0> def o.foo; end
=> nil
irb(main):191:0> o2=o.clone
=> #<Object:0x414be1b0>
irb(main):192:0> o2.foo
=> nil
irb(main):193:0> o3=o.dup
=> #<Object:0x414baee8>
irb(main):194:0> o3.foo
NameError: undefined method `foo' for #<Object:0x414baee8>
from (irb):194
from /usr/lib/ruby/1.8/yaml/rubytypes.rb:67

Csaba
 
K

Keith P. Boruff

Robert said:
They do both shallow copy.

Here's a difference:

=> false

So it looks like the major difference is that clone copies the state of the
original object and dup doesn't? At least in the context of "freeze"?
Probably because the path names are modified later on and the implementer
of find wanted to avoide side effects on the arguments. Or he wanted to
make sure that modifications to the argument objects don't affect find()
as it is likely to run comparatively long compared to other methods.

Got it! Thanks!

KPB
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,273
Latest member
DamonShoem

Latest Threads

Top