Object Oriented Programming

Constructor in Ruby

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


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

end

Notes

There can be multiple constructors with a different number or types of input parameters. This is known as overloading (in fact, methods can be overloaded as well).

Defaults can be set for cases where parameters aren't passed on object creation. This can be done by using the assignment operator which assigns the default value to an input parameter.


Example
class City
    def initialize(cityName = "No city provided", population = 0)
        #if no city name is provided during object creation, default string is assigned
        @cityName = cityName     

        #if no population parameter is provided during object creation, 0 is assigned
        @population = population
    end
end 

See Also
Related

Class Declaration and Structure

Documentation

Class - Ruby API

Add to Slack

< Class and Instance Variables   |   Instantiation >

© 2019 SyntaxDB. All Rights Reserved.