Object Oriented Programming
Constructor in Ruby
A constructor is a special method that builds the object when a new object is created.
class className def initialize(inputParameters) #set fields and run methods needed on instantiation here end end
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.
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
Class Declaration and StructureDocumentation