On Feb 1, 11:10 pm, "Chris Shea" <cms... / gmail.com> 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.