What's the difference between Ruby's dup and clone methods? describes the difference in the behavior of dup and clone. But when should I use dup, and when should I use clone instead?
Examples from actual projects which discuss why they used dup rather than clone, or vice versa, would be ideal for this question.
Alternatively, an explanation of why the two different methods exist would be helpful. This could refer to statements from the creators of Ruby, or an examination of methods like dup and clone in languages that influenced Ruby.
It is true that
clonecopies thefrozenstate of an object, whiledupdoes not:clonewill also copy the singleton methods of the object whiledupdoes not:Which leads me to the assumption that
cloneis sometimes understood as to provide a "deeper" copy thandup. Here are some quotes about the topic:Comment on
ActiveRecord::Base#initialize_dupfrom Rails 3:An article about deep copies in Ruby:
But then again, theres
deep_dupin Rails 4:and also
ActiveRecord::Core#dupand#clonein Rails 4:Which means that here, the word
dupis used to refer to a deep clone again. As far as I can see, there seems to be no consensus in the community, except that you should usecloneanddupin the case when you need a specific side effect of either one.Finally, I see
dupmuch more often in Ruby code thanclone. I have never usedcloneso far, and I won't until I explicitly need to.