This method is like a constructor of other object oriented programming languages.
when you want to initialize some class variables while creating an object, we use this method.
.
like any other ruby method,it starts with def keyword
class abc
def initialize(w,h)
@width, @height = w, h
end
end
Example
class Evon
# constructor method
def initialize(w,h)
@width, @height = w, h
end
# accessor methods
def printWidth
@width
end
def printHeight
@height
end
end
# create an object
b = Evon.new(35, 45)
# use accessor methods
x = b.printWidth()
y = b.printHeight()
puts "Width of the box is : #{x}"
puts "Height of the box is : #{y}"
0 Comment(s)