Exercise 1: Make a Rectangle Class
Explore how to create a Rectangle class in Ruby by defining height and width attributes and implementing an area instance method. Learn to use initialize methods and attribute readers to manage object state effectively in this hands-on exercise.
We'll cover the following...
We'll cover the following...
Problem statement
Write a Rectangle class with height and width attributes and an area() instance method.
- Populate these attributes through the
initialize(height, width)method. - Define attribute readers for these attributes.
Example
With your definition, consider the following code:
rect = Rectangle.new(5,10)
puts rect.height
puts rect.width
puts rect.area()
It’s expected to print:
5
10
50