Skip to content

Instantly share code, notes, and snippets.

@MelissaKaulfuss
Last active May 25, 2018 04:46
Show Gist options
  • Save MelissaKaulfuss/b70dd7a0cf158b6ea49c9ff597c1f810 to your computer and use it in GitHub Desktop.
Save MelissaKaulfuss/b70dd7a0cf158b6ea49c9ff597c1f810 to your computer and use it in GitHub Desktop.
the dup method in ruby

What's this #dup method do?

Doing a code read today in our monthly 10% time I started to read and document an internal event sourcing framework we've built in our team. I stumbled across the .dup method and so naturally I got sidetracked (losing sight of the high level) with StackOverflow posts, Ruby-Doc and my own IRB comparisons between it, and another method that appears quite similar -clone.

Importantly dup differs from clone in that it duplicates the object as a completely new record (if it's an ActiveRecord object no id is assigned however if it's a PORO a new object_id is assigned so it's completely different). The duped object has no direct assocation with the original at all. Thus, if you modify a duped object, you won't change the original object and that's because it's a “shallow” copy – it copies the object’s attributes only, not its associations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment