From: Robert Klemme Date: 2005-06-16T19:15:33+09:00 Subject: Re: sequentially output each hash key and value Charles L. Snyder wrote: > Hi, > > I have a snippet of code which > > 1. asks for a title from user > 2. opens a text file of the form : > > definition: blah blah blah > incidence: blah yah blah > category: yeah blah tah > . > . > > 3. puts everything to the left of the : into a hash as the keys, and > everything to the right in as matching values. > 4. Outputs it as "Title.htm" file in format I want > > My code works for (obviously) the key and value ONLY in the 1 > position What do you mean by that? > - Problem is I can't figure out how to get it to > sequentially iterate thru the whole hash table - should be easy, but > I can't make it work... Thanks in advance ! > > Here is my code: > > p "Enter a title..." > title = gets.chomp > talks_text = [] > dict = {} > IO.foreach("testfile.txt") do >> x| > if > y = /:/.match(x) > y = y.pre_match > z=/:/.match(x) > z = z.post_match > dict[y] = z > end > end Reading can be somewhat simplified: # untested IO.foreach("testfile.txt") do |line| if /^\s*(w+)\s*:\s*\b(.*)$/ =~ line dict[$1] = $2 end end > dict.sort This sort is useless as it will not sort the Hash but return an ordered array of arrays. You're only wasting CPU cycles here. > > File::open(title + '.htm', 'w') do |f| > f.puts "\n" + title + "\n bgcolor=#FFDEAD>\n" > f.puts "

" + title + "

" > f.puts "by Charles L. Snyder, MD
\n" > f.puts "
\n
\n" > f.puts "

" + dict.keys[1] + "

" + > dict.values[1] + "
" > f.puts "
HREF=\'javascript:window.history.back()\'>Back " f.puts > "
\n
\n" end File::open(title + '.htm', 'w') do |f| f.puts "\n" + title + "\n\n" f.puts "

" + title + "

" f.puts "by Charles L. Snyder, MD
\n" f.puts "
\n
\n" dict.sort.each do |key,value| f.puts "

" + key + "

" + value + "
" end f.puts "
Back " f.puts "
\n
\n" end Kind regards robert