Bhartee Rameshwar Sahare
Posted on February 19, 2023
clone:
- This method is a shallow copy of the object. Be aware that your attributes are unique.
- Changing the attributes of the clone will also change the original.
- create a new object with the same id, so all the changes made to that new object will overwrite the original record if hit .save.
user = User.first
User Load (0.2ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ? [["LIMIT", 1]]
=> #<User:0x0000563e2b9b3268 id: 1, name: "Jane Doe", dob: nil, gender: nil, created_at: Tue, 14 Feb 2023 12:45:36.528000000 UTC +00:00, updated_at: Tue, 14 Feb 2023 12:45:36.528000000 UTC +00:00>
new_user = user.clone
=> #<User:0x0000563e2bb8a0f0 id: 1, name: "Jane Doe", dob: nil, gender: nil, created_at: Tue, 14 Feb 2023 12:45:36.528000000 UTC +00:00, updated_at: Tue, 14 Feb 2023 12:45:36.528000000 UTC +00:00>
dup:
- Duped objects have no ID assigned and are treated as new records.
- This is a “shallow” copy as it copies the object’s attributes.
- create a new object without its ID being set, so you can save a new object to the database by hitting. save.
user = User.last
User Load (0.1ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT ? [["LIMIT", 1]]
=> #<User:0x0000563e2b9b1008 id: 3, name: "bhartee", dob: nil, gender: nil, created_at: Tue, 14 Feb 2023 12:45:57.223000000 UTC +00:00, updated_at: Tue, 14 Feb 2023 12:45:57.223000000 UTC +00:00>
new_user = user.dup
=> #<User:0x0000563e2c18a180 id: nil, name: "bhartee", dob: nil, gender: nil, created_at: nil, updated_at: nil>
Difference:
clone copies of the singleton class, while dup does not.
o = Object.new
=> #<Object:0x0000563e2c319a78>
> def o.foo
> 42
> end
=> :foo
> o.dup.foo
(irb):31:in `<main>': undefined method `foo' for #<Object:0x0000563e2bbd2508> (NoMethodError)
> o.clone.foo
=> 42
clone preserves the frozen state, while dup does not.
class Foo
attr_accessor :bar
end
o = Foo.new
o.freeze
o.dup.bar = 10
=> 10
o.clone.bar = 10
(irb):39:in `<main>': can't modify frozen Foo: #<Foo:0x0000563e2b9e8e18> (FrozenError)
💖 💪 🙅 🚩
Bhartee Rameshwar Sahare
Posted on February 19, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.