DEV Community

Cover image for Array clone and dup method in Ruby.
Bhartee Rameshwar Sahare
Bhartee Rameshwar Sahare

Posted on

Array clone and dup method in Ruby.

clone:

  1. This method is a shallow copy of the object. Be aware that your attributes are unique.
  2. Changing the attributes of the clone will also change the original.
  3. 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>
Enter fullscreen mode Exit fullscreen mode

dup:

  1. Duped objects have no ID assigned and are treated as new records.
  2. This is a “shallow” copy as it copies the object’s attributes.
  3. 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>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)