Chapter 2 - Methods and Classes

Exercise 3: Validation

In your Rectangle class from the previous exercise, modify both the width= and height= attribute writer methods to raise an error if a negative value is provided.

Solution

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

rectangle = Rectangle.new
rectangle.width = -2 # Raises an error!