On Sat, 26 Jun 2004 23:58:44 +0000, @*(&SPAM&)*optonline.net wrote: > #!/bin/env ruby > > # Read input from stdin only if not a tty. The only reason I gave such a > # constraint here was just to see that I could do it. It's one of the > # first things I do in learning a new language > if not STDIN.tty? > data = STDIN.read > end > > exit if not data > > > # PRINT THE WORD COUNT > > # 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) > > > # 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 > > printf("Longest Line Length: %d\n", line_length) > > ----- End of Program ----- > > > My question here isn't correctness as much as elegance. I'm fairly sure > the solutions I've provided are correct (maybe); I'm just wondering if > anyone has a better solution. > > Thanks, > Keith P. Boruff Hi, If you want you could get rid of the loop using inject: line_length = data.inject(0){ |m, l| m = (l.length > m ? l.length : m) } - 1 #the - 1 is for the extra newline character. I think however that for large files it may not be so efficient (since the whole file has to be loaded in memory). You could put everything in a loop for STDIN.each: # your initialization code ... line_length = 0 wc = 0 STDIN.each do |l| wc += l.split.length line_length = l.length if l.length > line_length end line_length -= 1 #show the result Regards, Kristof Bastiaensen