Jason Heppler Jason Heppler - 1 year ago 126
HTML Question

How to wrap Ruby strings in HTML tags

I'm looking for help on two things. 1) I'm looking for a way for Ruby to wrap strings in HTML. I have a program I'm writing that generates a Hash of word frequencies for a text file and I want to take the results and place it into an HTML file rather than print to STDOUT. I'm thinking each string needs to be wrapped in an HTML paragraph tag using readlines() or something, but I can't quite figure it out. Then, once I've wrapped the strings in HTML 2) I want to write to an empty HTML file.

Right now my program looks like:

filename = File.new(ARGV[0]).read().downcase().scan(/[\w']+/)
frequency = Hash.new(0)
words.each { |word| frequency[word] +=1 }
frequency.sort_by { |x,y| y }.reverse().each{ |w,f| puts "#{f}, #{w}" }

So if we ran a text file through this and received:

35, the
27, of
20, to
16, in
# . . .

I'd want to export to an HTML file that wraps the lines like:

<p>35, the</p>
<p>27, of</p>
<p>20, to</p>
<p>16, in</p>
# . . .

Thanks for any tips in advance!

Answer Source

This is a trivial problem.

#open file, write, and close

File.open('words.html', 'w') do |ostream|
  words = File.new(ARGV[0]).read.downcase.scan(/[\w']+/)
  frequency = Hash.new
  words.each { |word| frequency[word] +=1 }

  frequency.sort_by {|x, y| y }.reverse.each do |w,f| 
     ostream.write "<p>#{f}, #{w}</p>" 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download