create an instance of a class with a constructor in ruby

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.rb
class Person
  def initialize(name, age)
    @name = name
    @age = age
  end
  
  def introduce
    puts "Hi, my name is #{@name} and I am #{@age} years old."
  end
end
171 chars
11 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.rb
person1 = Person.new("Alice", 30)
person1.introduce # Output: Hi, my name is Alice and I am 30 years old.
106 chars
3 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