From: Mikael Brockman Date: 2004-06-27T09:30:54+09:00 Subject: Re: Writing UNIX 'wc' program "@*(&SPAM&)*optonline.net" <" kboruff\""@*.*optonline.net> (&SPAM&)> writes: > Hey all, > > I've been spending the last week learning Ruby. Prior to that, I had > spent some time learning Python. For various reasons, it looks like > I'm gravitating more to Ruby. > > That being said, I decided to write a small program similiar to the > UNIX 'wc' program. > > Right now, it's very stripped down being that it only accepts input > data from STDIN if not a tty and I also haven't yet implemented the > command line arguments. > > For the context of this post, I only included the logic that > gets/prints the word count and gets/prints the length of the longest > line since these are the ones I have questions about. Here it is: > > [...] > > # I'm wondering if there's an easier way to do this. It would > # be nice of the String::count method accepted regex patterns > # and not just strings. > > # As it stands, this method creates a seperate array of words > # for which I get the count of. I would've rather done this > # without the extra overhead but I guess it's no big deal: it works! > printf("Word Count: %d\n", data.split(/\s/).length) 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. > > # 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. mikael