From: Robert Klemme Date: 2006-05-10T00:49:34+09:00 Subject: Re: code snippet: can it be done better/shorter? 2006/3/1, dblack@wobblini.net : > Hi -- > > On Thu, 2 Mar 2006, Krekna Mektek wrote: > > > AFAIC See, this works all right, but my question is, just to learn the > > Ruby style, can this be done shorter (better)? > > > > class LineChecker > > def checkline(line) > > if line =~ /Checking:/ > > line =~ /<(.*?)>.*<(.*)>/ > > from = $1; rcpt = $2 > > from = "Unknown" if from == "" > > rcpt = "Unknown" if rcpt == "" > > return ([from,rcpt]) > > elsif line =~ /ClamAV-clamd\ result:\ / > > return $' > > else� > > return []� > > end > > > > end > > end > > Here's a slightly different way that might give you some ideas: > > class LineChecker > > REG=/<(.*?)>.*<(.*)>/ > > def checkline(line) > case line > when /Checking:/ > m = REG.match(line) > from, rcpt = m.captures if m > [from || "Unknown", rcpt || "Unknown"] > when /ClamAV-clamd result: / > $' > else > [] > end > end > end Usually using a RX in a constant is less efficient and in this case it's also less readable IMHO. Your piece as well as the original piece both return completely different things (a single return or multiple returns). I don't know whether that's intended but it might be a problem. There are other issues like using .* in a regexp - usually matching gets faster and more efficient with more specific patterns. But that's a more genral remark and not something specific about Ruby style. Kind regards robert