From: "David A. Black" Date: 2004-09-19T07:21:21+09:00 Subject: Re: Method improvement request .-- Hi -- On Sun, 19 Sep 2004, Charles Hixson wrote: > I'm sure there must be a more idiomatic+efficient way to do this, but I > can't figure it out. Any suggestions? > Also, I'm not sure all of the tests are necessary. Many of them were > added to avoid "Nil class does not implement..." messages. Is there a > better approach? > > # parse1 separates a chunk into the non-word stuff before it, the word > stuff, and the non-word stuff after it > # word stuff is letters, digits, hyphens, and periods > def parse1(chunk) > pb = /^([^-A-Za-z0-9]*)/ > pe = /([^-A-Za-z0-9]*)$/ > mtch = pb.match(chunk) > a = mtch[0] > mtch = pe.match(mtch.post_match) > b = mtch.pre_match > c = mtch[0] > #print " parse1:a #{a.inspect} " if a and > a.length > 0 > yield a if a and a.length > 0 > #print " parse1:b #{b.inspect} " if b and > b.length > 0 > yield b if b and b.length > 0 > #print " parse1:c #{c.inspect} " if c and > c.length > 0 > yield c if c and c .length > 0 > end The spacing got screwed up there, as you can see, but anyway -- I believe that pre_match and post_match will always be empty strings, if there's no match, not nil. So the "if a" test is not necessary (if I'm right). However, calling #[] on the results of a match will raise an exception (trying to call #[] on nil) if there was no match, so you have to be careful with the "a = mtch[0]" line. I wonder also whether it's useful to yield only non-empty strings. The caller then has to test the strings to see which of the positions they're from. It might be better to yield three things every time, so the caller knows what's being yielded. All of which leads me to this probably over-simplified code: def parse1(chunk) chunk.scan(/^(\W*)(\w+)(\W*)$/).flatten.each {|s| yield s} end (I've used \W and \w where you'd need to use something more custom-made -- though I don't think your character classes do what you want, because they don't include periods.) David -- David A. Black dblack@wobblini.net