Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Cloning and freezing objects

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 296
    Comment on it

    Suppose we have an object and that object is assigned to two different variables.
    Now if we make any changes to one variable the other variable's will automatically change.

    For example

    Obj_1 = [1,2,3]
    obj_2 = obj_1
    obj_2 << 4
    
    p Obj_1
    p obj_2

     

    It will print:

    
    [1,2,3,4]
    [1,2,3,4]


    In that situation, clone can be used. Clone create an independent copy of an object.It ensures that the value of an original object should not be affected by other objects.

    For example:

    obj_1 = [1,2,3]
    obj_2 = obj_1.clone
    obj_2 << 4
    
    p Obj_1
    p obj_2

    It will print:

    [1,2,3]
    [1,2,3,4]

    Here changes made in obj_2 does not affect obj_1.

    Now suppose we have an object and we do not want any changes to that object, In that case, we freeze the object. Let us look at the example below where we freeze an object and try to modify it:

     

    str = "one"
    str.freeze
    str << "two"


     
    The above code will give you a RuntimeError with a message that "can't modify frozen string".
    However, this is still possible:

    number = [1,2,3,4]
    number.freeze
    number = [1,2,3]
    
    p number

     

    It will print:

    [1,2,3]

    Here you can see that the above code won't raise any error because variables hold the reference of objects and the freeze was executed on an object only, so we can change the variable to refer to a different object.

    To check if an object is frozen or not we can use frozen? method as:

    number.frozen?   // will return true

     

 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: