To create an instance of a class with a constructor in ruby, you first define the class and the constructor method within it. The constructor method is typically defined as initialize
. Here is an example of a class with a constructor:
main.rb171 chars11 lines
Once the class is defined, you can create an instance of it by calling the new
method on the class and passing in the arguments required by the constructor method. Here is an example:
main.rb106 chars3 lines
In this example, we created an instance of the Person
class and assigned it to the variable person1
. We passed in the arguments "Alice" and 30 to the constructor method, which sets the instance variables @name
and @age
of the new object. Finally, we called the introduce
method on the person1
object to print out a message with the object's name and age.
gistlibby LogSnag