To create a class with a constructor in Ruby, you use the initialize
method. Here's an example:
main.rb83 chars7 lines
In this example, we define a class Person
with an initialize
method that takes two arguments - name
and age
. Inside the initialize
method, we assign these values to instance variables @name
and @age
.
The instance variables @name
and @age
are now available throughout the class, and can be accessed by any instance method of the class.
To create an instance of the Person
class, we call the new
method:
main.rb32 chars2 lines
This creates a new instance of the Person
class with name
set to "John"
and age
set to 30
.
Now we can access the instance variables of the person
object:
main.rb47 chars3 lines
Note that we need to define name
and age
methods to access the instance variables @name
and @age
.
gistlibby LogSnag