How to Define a Class Constructor in Ruby?

A class constructor in Ruby is defined by adding an "initialize" method to the class like so:

class Entity
  def initialize
    puts "Object instance was created"
end # output: "Object instance was created"

The initialize method is called each time an object instance of the class is created using the new method. Any arguments passed to new are automatically be passed to the initialize method. For example:

class Person
  def initialize(name, age)
    @name = name
    @age = age

  def name

  def age

person ="John", 22)
puts "#{} is #{person.age} years old"

# output: "John is 22 years old"

Hope you found this post useful. It was published . Please show your love and support by sharing this post.