Chapter 2 - Methods and Classes

Exercise 2: Rectangle class

Create a Rectangle class. Add width and height attributes, with methods to read and write each. (There’s a shortcut for doing all that, so if you know the shortcut, by all means use it!) Then add an area method that returns the area of the rectangle. (You can calculate this by multiplying the width attribute by the height attribute.)


class Rectangle
  attr_accessor :width, :height

  def area
    width * height

rectangle =
rectangle.width = 2
rectangle.height = 4
puts rectangle.area