From: Charles Hixson Date: 2004-09-20T07:24:29+09:00 Subject: Re: Method improvement request .-- Bill Guindon wrote: >On Sun, 19 Sep 2004 06:29:43 +0900, 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? >> >> > >Might be easier if you could show a sample of what you're starting >with, and what you'd like it to become. If the sample is large, you >can always paste it into codepaste (http://www.codepaste.org), and >just put the link to it in the email > > > >>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? >> >> > >yes, those still drive me nuts too, but I'm learning :) > > > >>yield a if a and a.length > 0 >> >> > >this can be written as... > yield a if a unless a.empty? > >it won't get to the 'unless' if 'a' is nil, so it dodges the missing >method error. > > > >>return "" unless chunk.respond_to?("[]") >> >> > >you can avoid this by forcing the issue... > chunk = [] << chunk > chunk.flatten! > >now chunk is an Array no matter what. could be an empty one, or could >contain useless objects, but it's an Array ;) > >Also... I think parse2 and parse3 can be combined into something like this: > > p2 = p1.split(/(\.\.\.|--)/) > p2.delete('--') > p2.delete('...') > p2.each {|p3| yield p3} > >if you can change your editor from tabs to 2 spaces, you're code will >hold up better in the emails. > OK, I've copied it over to codepaste here: http://www.codepaste.org/paste/comment/218 http://www.codepaste.org/view/paste/163?show_comments=1 etc. (How long does code stay up here? I never knew the site existed.) But I think that I put the relevant pieces in the first e-mail. However, I don't intend that elipsis and double-dashes be deleted. They merely need to be parsed separately from the words that they appear with. They do contain significant meaning, so merely deleting them would be anti-productive. Also: Is chunk = [] << chunk chunk.flatten! return chunk better in some way than return "" unless chunk.respond_to?("[]") I could see, perhaps, return "" if not chunk or chunk.empty? but I'd been reading that it was more Ruby-esque to use duck typing and the responds_to? test. That's one reason I didn't do return "" if chunk.nil? And I'm still not certain what I should really be doing in such a case. What I really want to do is avoid returning nil. I want to skip over the processing of this case without aborting the calling process (likely an each). If this were a loop, then the command would be next rather than break or retry.