From: Robert Klemme Date: 2008-10-26T19:34:51+09:00 Subject: Re: regular expressions and conditionals On 26.10.2008 01:02, Caleb Clausen wrote: > On 10/25/08, Matt Harrison wrote: >> I'm writting a little program to convert some source files to html. >> >> I'm using regexp's to determine the content of each line and format it >> accordingly. For example, if the line starts with a #, then it should be >> output with a div (and id set to 'comment'). >> >> The problem is with matching the regular expressions. If I do this: >> >> f = File.new("myfile", "r") >> while !f.eof? >> line = f.gets >> >> if line.match(/^# (.*)/) >> puts "
#{line.match(/^# (.*)/)[0]}
" >> end >> end >> > > I think what you're trying to write is a little more like this: > f = File.new("myfile", "r") > while line = f.gets > if line.match(/^# (.*)/) > line="
#{line.chomp}
\n" > end > puts line > end Even better is # Use the block form of File.open! File.new("myfile", "r") do |f| f.each do |line| line.chomp! case line when /^# *(.*)/ puts "
# {$1}
" else puts line end end end or, for that matter File.foreach("myfile") do |line| line.chomp! case line when /^# *(.*)/ puts "
# {$1}
" else puts line end end Kind regards robert