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"

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.