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
end

Entity.new # 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
  end

  def name
    @name
  end

  def age
    @age
  end
end

person = Person.new("John", 22)
puts "#{person.name} 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.