Another Page
Create a Ruby definition which adds
some small methods to the standard String and Array classes which
might be of some use in writing a program to generate HTML output.
The methods are:
String#hesc
Add the
hesc method to the
String class. It takes no
arguments, and returns a copy of the string with each of the characters
<,
> and
& replaced with their appropriate
HTML entities. For instance,
"I like less-than (<) and ampersand (&)".hesc
returns the string
"I like less-than (<) and ampersand (&)"
String#tag
Add the
tag method to the
String class. It takes one
argument, which is a string giving an HTML tag.
The
tag method returns a new string, constructed of the
argument surrounded by angle brackets, and followed by the first
word of the argument as a closing tag, leading with
</ and
ending with
>. Between is the original string after
processing through
hesc.
For instance,
"foo".tag("i"); returns the string
<i>foo</i>.
The purpose of the
“first word of the argument” rule is to produce a correct closing tag when
the tag includes attributes. The “word” is delimited by spaces.
For instance,
"The Many Uses Of &".tag("h1 color=\"blue\"")
will return
<h1 color="blue">The Many Uses Of &</h1>
Array#tag
This simply returns a copy of the array with tag applied
to each member.
Array#nest
This takes a single argument which is a tag under the same rules as
String#tag. It returns a copy of the array, with an additional
item at front and another at back. The new items are strings, giving
the opening and closing version of the tag specified as an argument.
These are formed the same way as in the tag method.
Place your Ruby code in a file which can be brought in with
load.
For instance:
irb(main):001:0> load "htmlgen.rb"
=> true
irb(main):002:0> "a < b == (a <= b && a != b)".hesc
=> "a < b == (a <= b && a != b)"
irb(main):003:0> "a < b == (a <= b && a != b)".tag('span class="form"')
=> "<span class=\"form\">a < b == (a <= b && a != b)</span>"
irb(main):004:0> ["a","b","c","d"].tag("i")
=> ["<i>a</i>", "<i>b</i>", "<i>c</i>", "<i>d</i>"]
irb(main):005:0> ["a","b","c","d"].tag("i").nest("tr id=\"foo\"")
=> ["<tr id=\"foo\">", "<i>a</i>", "<i>b</i>", "<i>c</i>", "<i>d</i>", "</tr>"]
irb(main):006:0> ("1".."10").to_a.tag("td").nest("tr").join
=> "<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td></tr>"
irb(main):007:0> ["al","bill","sally","joe"].tag('div color="blue"').nest("div")
=> ["<div>", "<div color=\"blue\">al</div>", "<div color=\"blue\">bill</div>", "<div color=\"blue\">sally</div>", "<div color=\"blue\">joe</div>", "</div>"]
irb(main):008:0> ["a","b","c"].nest("a href=\"nowhere\"")
=> ["<a href=\"nowhere\">", "a", "b", "c", "</a>"]
When your methods work, are nicely formatted and documents,
submit the file using
this
form.