Constructors or the initialize() method provides us a way to initialise the attributes of the class while an object is created.
There are two types of Constructor :
The initialize() method with no arguments is the Default Constructor. It is called so because, even though we don't call the initialize() method, it is automatically called at the time of Object creation.
Let us see in the below example.
class Human def initialize() puts "initialize() method is called during object creation" end end human1 = Human.new()
In the above example, we have created the Human class,
class Human def initialize() puts "initialize() method is called during object creation" end end
With the initialize method,
def initialize() puts "initialize() method is called during object creation" end
Just to demonstrate that you don't have to call the initialize() method separately. But it would be called automatically, at the time of object creation.
human1 = Human.new()
So, the moment we create the object using Human.new(), initialize() method is called automatically and we get the below output.
initialize() method is called during object creation
Now, let us see, how can we initialise all the attributes of the Human class using the Constructor with Arguments.
Let us take the same Human class from the previous tutorial.
class Human def initialize(name, food, language) @name = name @food = food @language = language end def eat() puts "#{@name} eats #{@food}" end def speak() puts "#{@name} speaks #{@language}" end end human1 = Human.new("John", "Burger", "English") human2 = Human.new("Rakhi", "Rice", "Hindi") human1.eat() human1.speak() human2.eat() human2.speak()
Now, the above example has a structured way of defining the attributes of the class(i.e. name, food and language).
All we have done is, while creating the object human1, we have passed the values, "John", "Burger" and "English" as Arguments.
human1 = Human.new("John", "Burger", "English")
And what happens is, the constructor, init(...) with three Arguments is called.
def initialize(name, food, language) @name = name @food = food @language = language end
And "John" gets initialised to the variable name, "Burger" to food and "English" to the variable language.
And self refers to human1 object.
But! Hold on!
The values are not yet a part of the human1 Object. They becomes a part of human1 Object in the next lines.
@name = name @food = food @language = language
And
@name = name
Takes the value John from the local variable name and puts it to the name attribute of the Human class.
Similarly, the next two lines,
@food = food @language = language
Assigns the values Burger and English to the food and language attribute of the human1 object.
And the human1 object has the values now.
Similarly, the next line,
human2 = Human.new("Rakhi", "Rice", "Hindi")
Assigns the values to the human2 object.