What is the .new method?
.new method is a class method that is commonly used to create a new instance of a class. It is typically associated with class constructors and is used to instantiate object from a class.
Example:
class Person
attractive_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
end
# Using .new to create a new instance of the Person class
person1 = Person.new("John", 30)
puts personal.name # Output: John
puts personal.age # Output: 30
In this example, the .new method is called on the 'Person' class to create a new instance of the class, and it calls the 'initialize' method to set the initial values for the instance variables ('name' and 'age' in the case).
How and when to use .new method?
You use the .new method when you want to create object of a particular class. This is a common practice in object-oriented programming where classes are used to model and structure code, and objects are instance of those classes that hold specific data and behavior.
Top comments (0)