From: Gavin Sinclair Date: 2004-06-27T09:37:24+09:00 Subject: Re: Writing UNIX 'wc' program A couple of tips. * ARGF is your friend when it comes to input; it is a virtual file that gets all input from named files or all from STDIN. * 'unless' is a substitute for 'if not'. * 'puts' is worth knowing about (I use 'printf' 1% of the time): puts "Word count: " + data.split(/\s/).length puts "Longest Line Length: #{line_length}" * As far as elegance goes, see how you like this: longest_length = data.split(/\n/).map { |l| l.length }.max The way you've done it will perform better though, I expect. Cheers, Gavin On Sunday, June 27, 2004, 10:03:02 AM, wrote: > ----- Beginning of Program ----- > #!/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 -----