ruby-constructor

What is constructor in ruby?

A constructor is a special method that builds the object when a new object is created.

How to define a constructor in ruby?

class className 
   def initialize(inputParameters) 
       #set fields and run methods needed on instantiation here 
   end 
end

Constructors are declared via the initialize method and get called when you call on a new object to be created.Using the code snippet below, calling Order.new acts as a constructor for an object of the class Order.

Example

class Order
  def initialize(customer, meal, beverage)
    @customer = customer
    @meal = meal
    @beverage = beverage
  end
end

Leave a Reply

Your email address will not be published. Required fields are marked *