From: Charles Hixson Date: 2004-09-20T06:39:25+09:00 Subject: Re: Method improvement request .-- YANAGAWA Kazuhisa wrote: >In Message-Id: <414CA862.7090402@earthlink.net> >Charles Hixson writes: > > > >># parse1 separates a chunk into the non-word stuff before it, the word >>stuff, and the non-word stuff after it >> >> >String#split includes a captured portion in a result array, so you can do: > irb(main):008:0> "!@#456&*(".split(/([\w\-.]+)/, 3) > => ["!@#", "456", "&*("] > irb(main):009:0> "456&*(".split(/([\w\-.]+)/, 3) > => ["", "456", "&*("] > irb(main):010:0> "!@#456".split(/([\w\-.]+)/, 3) > => ["!@#", "456", ""] >If a string has extra word-nonword pairs, you should consider that. > > Unfortunately, when I take this approach, I get a lot of nil's (and the string isn't actually only split into three's, though I suppose you are implying I could to it iteratively on the tail...which could work). >># parse2 takes a hunk of word stuff, and possibly separates it at a >> >> >(snip) > > >># parse3 takes a hunk of word stuff, and possibly separates it at an >> >> >So you just do: > > def parse_chunk(chunk, regexp) > chunk.split(regexp, 3).each {|v| yield(v)} > end > > def parse2(chunk, &block) > parse_chunk(chunk, /(\.\.\.)/, &block) > end > > def parse3(chunk, &block) > parse_chunk(chunk, /(--)/, &block) > end > I'm still in the early stages of picking up Ruby (again...the first time the libraries were too immature for me to use them), so I'm having difficulty envisioning how one would chain those parse methods together. &block should clearly be a block of code, but I don't see *what* the code should be. There are many Ruby idioms that I'm less than totally fluent with, and that's one of them. (I just recently figured out that if a routine has yields, then you probably shouldn't have returns. And I'm still not certain that an error check at the start shouldn't just return an invalid value...but for safety I've been rewriting things to do a logic branch around the normal code and yield an invalid value. It works, but I'm not really sure it's the best way.) Sorry, I've done a lot of programming, but this is my first try at a substantial piece in Ruby. So I can generally make things work, but frequently go the long way around to do it.