From: Chris Shea Date: 2007-02-03T01:00:10+09:00 Subject: Re: halving a string On Feb 2, 6:53 am, "Trans" wrote: > On Feb 1, 11:30 pm, "Chris Shea" wrote: > > > > > On Feb 1, 9:20 pm, "Trans" wrote: > > > > On Feb 1, 11:10 pm, "Chris Shea" wrote: > > > > > I have a vacuum fluorescent display in my office, and I've been > > > > messing around with it. Now that I've figured out how to communicate > > > > with the serial connection it's time for some fun. Its shortcoming is > > > > its 2 lines of 20 chars. So I naturally wrote a fortune cookie program > > > > for it. > > > > > I want to make adding new fortunes easy (and without having to figure > > > > out myself where to force a line break), so I basically need to split > > > > a string (approximately) in half at a word boundary. This is what I > > > > have: > > > > > class String > > > > def halve > > > > first_half = '' > > > > second_half = self > > > > until first_half.length >= length / 2 > > > > match = / /.match(second_half) > > > > first_half << match.pre_match << ' ' > > > > second_half = match.post_match > > > > end > > > > [first_half.strip, second_half] > > > > end > > > > end > > > > > I have a feeling there's a one-line regexp that can do this. Am I > > > > right? If not, is there a better way? > > > > untested but... > > > > i = [0..str.size / 2].index(' ') > > > first_half, second_half = str[0...i], str[i..-1].strip > > > > however, you might just prefer > > > > require 'facets/core/string/word_wrap' > > > str.word_wrap(20) > > > > T. > > > Tested, and failed. The index returns the position of the very first > > space. (Also, it would have to be str[0..(str.size / 2)].index(' ') > > but, still, it's no good). > > ah, size/2 has to be added to i, then it works. > > > Word wrapping is wrong for the occasion, as I'd like to split even > > lines less than 20 chars, and have them of approximately equal length. > > not sure i understand, the size can be set, for example: > > word_wrap(str.size/2) > > t. I thought of that, but: irb> str = "longlongword bit bits" irb> puts str.word_wrap(str.size/2) longlongwo rd bit bits => nil