From: "@(nil_spam)optonline.net" <" kboruff\""@...> Date: 2004-06-27T10:18:03+09:00 Subject: Re: Writing UNIX 'wc' program Mikael Brockman wrote: > How about something like this? > > | class String > | def match_count (pattern) > | count = 0 > | scan (pattern) { count = count + 1 } > | return count > | end > | > | def word_count > | match_count /\w+/ > | end > | end > | > | puts "Word Count: #{data.word_count}" > > Or put the methods outside of String if you prefer. This is good. I'll give it a shot. > > >># GET THE LENGTH OF THE LONGEST LINE >> >># If there's a more elegant solution than what I have below, I'm all >># ears >>line_length = 0 >>data.split(/\n/).each do |line| >> line_length = line.length if line_length < line.length >>end > > > I'd write something like > > | maximum_length = 0 > | data.each_line do |line| > | if line.length > maximum_length then > | maximum_length = line.length > | end > | end > > which doesn't need to keep all lines in an array. This is good too. However, this solution keeps the newline at the end of each line in the iteration so my longest line length of my test data is one more. In keeping with the actual wc program, it doesn't seem to count the new line. To add to your solution to fix this, I did this: maximum_length = 0 data.each_line do |line| line.chomp! if line.length > maximum_length then maximum_length = line.length end end Keith Boruff