I need help figuring out a programming problem that I've been working on.
The problem description:
Write a function in Ruby that accepts an HTML document (a string) and a keyword (also a string). The function will find all occurrences of the keyword in the HTML string after the <body>
element unless the keyword appears within an HTML tag, then surround the string found with tags to ``highlight’’ the keyword. For example,
<span style="background-color: blue; color: white">keyword</span>
You will have to be careful not to highlight strings occurring within an HTML tag. For example, if the keyword is ``table’’, you wouldn’t want to mark up this:
<table width="100%" border="0">
What I have done so far:
puts "Welcome to the HTML keyword highlighter!"
puts "Please Enter A Keyword: "
keyword = gets.chomp
canEdit = false
infile = File.new("desktop/code.html", "r")
outfile = File.new("Result.html", "w")
infile.each{ |i|
if (i.include? "<body>")
canEdit = true
end
if (i.include? "</body>")
canEdit = false
end
if(canEdit == true)
keyword.gsub(keyword, "<span style=\"background-color: yellow; color: black\">#{keyword}</span>")
outfile.write i
end
outfile.close()
infile.close()
}
The error I receive currently:
Welcome to the HTML keyword highlighter!
Please Enter A Keyword:
simple
/Users/Eva/Desktop/Personal/part4_program.rb:16:in `each': closed stream (IOError)
from /Users/Eva/Desktop/Personal/part4_program.rb:16:in `<main>'
I'm unsure what is causing the error and could use some guidance to fix the issue. I am also wondering if this program is heading in the right direction as an answer to the programming problem. I know Nokogiri is already available as a resource but I had hoped not to have to use it unless its thought to be a better option.