In this article, you will learn how to use the Ruby clone method.
Using the clone method
The clone method in Ruby creates a new object that is a copy of the original object. It creates a shallow copy, meaning that it copies only the object’s immediate values, such as numbers and strings, and not the objects referred to by instance variables.
Here are the basic steps to use the clone method in Ruby:
Create an object that you want to clone. For example, let’s create a class called Person with instance variables @name and @age:
class Person attr_accessor :name, :age def initialize(name, age) @name = name @age = age end end person1 = Person.new("John", 30)
Clone the object using the clone method. The clone method is called on the object you want to clone. For example, let’s clone person1:
person2 = person1.clone
Modify the cloned object. You can modify the cloned object without affecting the original object. For example, let’s change the name of person2:
person2.name = "Jane"
Verify that the original object is unchanged. You can verify that the original object is unchanged by printing its values. For example:
puts person1.name # Output: John puts person1.age # Output: 30
And the cloned object has the new name value:
puts person2.name # Output: Jane puts person2.age # Output: 30
Note that the clone method creates a new object with a new object ID. The cloned object is not equal to the original object, but its attributes have the same values as the original object.