Chapter 3 - Inheritance

Exercise 1: Square class

In the Chapter 2 bonus exercises, we created a Rectangle class like this:

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 create a subclass of Rectangle, named Square. Square should override the width= method to set both the width and height to the given value when called. It should do the same with the height= method. (Don’t worry about checking whether the values are negative.) All other methods should be inherited from Rectangle. The area method should work without any need to override it.

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

Exercise 2: Cupcakes

We have a Confection class representing baked desserts below. Your job is to create a new subclass of Confection, named Cupcake. Cupcakes need to be baked just like other confections, but they also need to be frosted afterward.

Write a prepare method for your Cupcake class that prints "Baking at 350 degrees for 25 minutes.", and then prints "Applying frosting." Do this without duplicating the puts line from the prepare method of the Confection class.

class Confection
  def prepare
    # Don't duplicate this line in the subclass!
    puts "Baking at 350 degrees for 25 minutes."
  end
end

# CREATE YOUR Cupcake SUBCLASS HERE!

# The below code should output the following
# 2 lines of text:
#
# Baking at 350 degrees for 25 minutes.
# Applying frosting.
cupcake = Cupcake.new
cupcake.prepare

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