Chapter 2 - Methods and Classes
Exercise 1: HTML methods
We need to create a web page, and typing all the HTML out by hand would be pretty tedious. Let’s create some methods to help us out.
An HTML paragraph tag is used to mark text in a web page. It looks like this:
Between the <p>
and </p>
tags, we can put whatever text we want.
So let’s start there. Create a method named paragraph
that takes a string as a parameter. It should create a new string that starts with <p>
, ends with </p>
, and contains the parameter string in the middle. Don’t just print the string with puts
inside the method, though; let the string be the method’s return value, and let the caller print it.
HTML also has image tags, which look like this:
The src
, width
, and height
attributes of the tag contain information that helps the browser display the image. The src
attribute specifies the file that the image should be loaded from, and the width
and height
attributes specify how wide and how tall the image should appear.
Now, create an image
method that returns an img
tag as a string. It should take 3 parameters: an image source string, a width, and a height. The width and height values should be optional, and should use a default of 100
for each. Interpolate the parameters into the HTML string as the attribute values.
After defining the paragraph
and image
methods, try calling them a few times to output some HTML, with image file names and text of your choosing.
When you’re ready, have a look at the solution.
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.)
When you’re ready, have a look at the solution.
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.
When you’re ready, have a look at the solution.