Ruby also supports constructors like other Object Oriented Languages. Constructors are used to initialize the instance variables. In most of the Object Oriented Languages constructors has the same name as that of the class, and does not have any return type. Ruby has changed this convention and in this constructors are defined using the initialze keyword.
It is written like any other ruby method starting with the def keyword. Whenver any instance of the class is created the initializer method is automatically called. It can also be overloaded like we used to overload the constructors in Object Oriented Languages like Java, C++ e.t.c
A simple program to demonstrate the use of constructors in Ruby is given below :
# player.rb
# define class Player
class Player
def initialize
@team = "Aussie"
@country = "Australia"
end
def display
puts "Player belongs to #{@team}"
puts "Player lives in #{@country}"
end
end
p1 = Player.new()
p1.display()
puts "Instance Variables are = " + p1.instance_variables.to_s
When we execute it, we get the following output :
taran@taran-System-Product-Name:~/Documents/ruby_prgms$ ruby aa.rb
Player belongs to Aussie
Player lives in Australia
Instance Variables are = [:@team, :@country]
0 Comment(s)