Chapter 4 - Initializing instances

Exercise 1: Initializing rectangles

Remember our Rectangle class from previous chapters?

class Rectangle
  attr_reader :width, :height

  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

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. When you’re done, this code should work:

rectangle = Rectangle.new(2, 4)
puts rectangle.area # Output: 8

When you’re ready, have a look at the solution.

Extra Credit: For bonus points, revise the initialize method to take keyword arguments instead of positional arguments!