What is the difference between dup and clone in Ruby?
Last updated
Both make a shallow copy (nested objects are shared by reference), so use something like
Marshalfor a deep copy.clonepreserves the frozen state and the singleton class (per-object methods).dupreturns an unfrozen copy without singleton methods.Both call
initialize_copy, andclone(freeze: false)skips copying the frozen status.
- https://docs.ruby-lang.org/en/3.3/Kernel.html
- https://dev.to/appsignal/diving-into-rubys-dup-and-clone-8fa
- https://docs.ruby-lang.org/en/3.3/Object.html
- https://medium.com/@eva.barczykowska/clone-and-dup-in-ruby-e7a98686617c
- https://medium.com/@giri14/difference-between-clone-and-dup-in-rails-8cc33a97811d