From: Rob Biedenharn Date: 2007-03-14T05:23:58+09:00 Subject: Re: perl to ruby On Mar 13, 2007, at 3:59 PM, Chad Perrin wrote: > On Wed, Mar 14, 2007 at 04:46:43AM +0900, Martin DeMello wrote: >> On 3/14/07, Chad Perrin wrote: >>> On Tue, Mar 13, 2007 at 05:36:20PM +0900, Martin DeMello wrote: >>>> >>>> or for efficiency >>>> >>>> File.open("/etc/passwd", "r") {|f| id = >>>> f.grep(/#{usr}/).first.split(/:/).at(2).to_i} >>> >>> . . . or for more readability: >>> >>> File.open("/etc/passwd", "r") do |f| >>> id = f.grep(/#{usr}).first.split(/:/).at(2).to_i >>> end >>> >>> I'm sure greater readability can be had by rewriting that >>> entirely, but >>> I found the multiline braces approach suboptimal, personally. YMMV. >> >> And the fact that my paste put a line break where it did didn't help >> :) that was supposed to be on one line - didn't realise how long it >> had gotten. > > Hmm. It should have occurred to me that was meant to be all one line. > > I think lines that long should usually be broken up for readability > anyway. Usually. > > -- > CCD CopyWrite Chad Perrin [ http://ccd.apotheon.org ] > "The first rule of magic is simple. Don't waste your time waving your > hands and hopping when a rock or a club will do." - McCloctnick the > Lucid > File.open("/etc/passwd", "r") do |f| id = f.detect {|line| line =~ /\A#{usr}:/}.split(/:/)[2].to_i end using grep will read all the lines, but detect will stop after finding the first line for which the block is true. I also suggest bracketing your regexp with \A (beginning of string) and ':' (separator in /etc/passwd) so searching for, say, "0", doesn't give you the root account. You probably also want to rescue exceptions that will arise if the usr is not found. -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com