Object References In Ruby | Clone and Dup in Ruby
Object References In Ruby
In Ruby, clone and dup are used to create shallow copies of an object, but they behave slightly differently. Both are used to create a copy of an object, but they have somewhat different behavior.
1. Dup:
The dup method will create a shallow copy of an object. A shallow copy means the object itself is duplicated, any object references by the original object are not duplicated. Changes made to the cloned object will not affect the original object. Dup allows modifications to the frozen state object.
statement1 = "What's up".freezestatement2 = statement1.dupstatement2 << " Nice to meet you"puts statement1 # Output: What's upputs statement2 # Output: What's up Nice to meet you
statement1 = "What's up".freeze
statement2 = statement1.dup
statement2 << " Nice to meet you"
puts statement1 # Output: What's up
puts statement2 # Output: What's up Nice to meet you
# FROZEN object
statement1 = "What's up".freezestatement2 = statement1.dupstatement2 << " Nice to meet you"puts statement1 # Output: What's upputs statement2 # Output: What's up Nice to meet you
statement1 = "What's up".freeze
statement2 = statement1.dup
statement2 << " Nice to meet you"
puts statement1 # Output: What's up
puts statement2 # Output: What's up Nice to meet you
2. Clone:
The clone method also creates a shallow copy of an object. Unlike dup, the clone does not allow modifications to the frozen state objects.
statement1 = "What's up".freezestatement2 = statement1.clonestatement2 << " Nice to meet you"puts statement1 # Output: What's upputs statement2 # Output: What's up Nice to meet you
The clone method also creates a shallow copy of an object. Unlike dup, the clone does not allow modifications to the frozen state objects.
statement1 = "What's up".freeze
statement2 = statement1.clone
statement2 << " Nice to meet you"
puts statement1 # Output: What's up
puts statement2 # Output: What's up Nice to meet you
# FROZEN object
statement1 = "What's up".freezestatement2 = statement1.clonestatement2 << " Nice to meet you"puts statement1puts statement2
# Output: can't modify frozen String: "What's up" (FrozenError)
So, both dup and clone provide a way to create a copy of an object, but depending on requirements, you have to choose one over the other, whether you want to allow modification to the frozen object.
statement1 = "What's up".freeze
statement2 = statement1.clone
statement2 << " Nice to meet you"
puts statement1
puts statement2
# Output: can't modify frozen String: "What's up" (FrozenError)
So, both dup and clone provide a way to create a copy of an object, but depending on requirements, you have to choose one over the other, whether you want to allow modification to the frozen object.
Comments
Post a Comment