Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • When to use dup, and when to use clone in Ruby?

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 97
    Comment on it

    Clone copies the exact copy of the original (same address.id) and the dup copy is a new record (address.id = nil). Any changes you will made in the clone copy will be changed the original object, but any changes to the dup copy attributes will remain isolated.

    for example:

    pry> original = Profile.find(5)
    
      Profile Load (0.7ms)  SELECT  "profiles".* FROM "profiles" WHERE "profiles"."id" = ? LIMIT 1  [["id", 5]]
    
    #<Profile id: 3, first_name: "david", last_name: "backham", email: nil, created_at: "2015-01-10 17:37:00", updated_at: "2015-01-10 17:37:00">
    

    pry> clone_copy = original.clone
    #<Profile id: 3, first_name: "david", last_name: "backham", email: nil, created_at: "2015-01-10 17:37:00", updated_at: "2015-01-10 17:37:00">
    

    pry> dup_copy = original.dup
    #<Profile id: nil, first_name: "david", last_name: "backham", email: nil, created_at: nil, updated_at: nil>
    

    Note: With CLONE you can copy any singleton methods of an object but DUP does not support this.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: