Instructions
Create a Rectangle class with:
initialize(width, height)widthandheightreader attributesareamethod returning width * heightperimetermethod returning 2 * (width + height)square?method returning true if width equals height
Hints:
- Use attr_reader :width, :height
- Area = width * height
- Perimeter = 2 * (width + height)
Your Code
class Rectangle
attr_reader :width, :height
def initialize(width, height)
@width = width
@height = height
end
def area
width * height
end
def perimeter
2 * (width + height)
end
def square?
width == height
end
end
RSpec.describe Rectangle do
let(:rect) { Rectangle.new(4, 5) }
let(:square) { Rectangle.new(3, 3) }
it "has width and height" do
expect(rect.width).to eq(4)
expect(rect.height).to eq(5)
end
it "calculates area" do
expect(rect.area).to eq(20)
end
it "calculates perimeter" do
expect(rect.perimeter).to eq(18)
end
it "knows if it is a square" do
expect(rect.square?).to be false
expect(square.square?).to be true
end
end
Results
Click "Run Tests" to see results