Chapter 4 - Initializing instances
Exercise 1: Initializing rectangles
Remember our Rectangle class from previous chapters? Your next task is to add an initialize method that takes two parameters: a width and a height. Assign those values to the width and height attributes of the new instance. You should utilize the existing validation in the attribute writer methods, so that an error is raised if a negative value is passed.
Solution
class Rectangle
attr_reader :width, :height
# New code here!
def initialize(width, height)
self.width = width
self.height = height
end
def width=(value)
if value < 0
raise "Width can't be negative!"
end
@width = value
end
def height=(value)
if value < 0
raise "Height can't be negative!"
end
@height = value
end
def area
width * height
end
end
rectangle = Rectangle.new(2, 4)
puts rectangle.area # Output: 8Extra Credit: For bonus points, revise the initialize method to take keyword arguments instead of positional arguments!
class Rectangle
# ...
def initialize(width:, height:)
self.width = width
self.height = height
end
# ...
end
rectangle = Rectangle.new(width: 2, height: 4)
puts rectangle.area # Output: 8