Chapter 2 - Methods and Classes

Exercise 1: HTML methods

Create a method named paragraph that takes a string as a parameter and returns a <p> HTML tag. 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.

Then, 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 src, width, and height 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.

Solution

def paragraph(text)
  "<p>#{text}</p>"
end

def image(source, width = 100, height = 100)
  "<img src='#{source}' width='#{width}' height='#{height}'/>"
end

puts paragraph("Hello, world!")
puts image("puppy.jpg", 800, 600)