On Jan 21, 1:12 pm, "Michael W. Ryder" <_mwry... / worldnet.att.net>
wrote:
> I am trying to find an easier way to split a string into printable
> lines.  I could use the method of checking for a space using a loop and
> going back from the desired length or I could use the following:
>
> def strbrk(str, len)
>    if str.length <= len
>      return str.length
>    end
>    tmp = str[0...len].reverse
>    x = tmp =~ / /
>    if x == nil
>      return -1
>      else
>        return len - x
>    end
> end
>
> I could not find any way to get a regexp to search from the end of the
> string which would have eliminated the need to reverse the string.

def str_break( str, len )
  str.size > len and str[0..len].rindex(' ') or str.size
end



str = "\
I don't necessarily need code examples -- but if anyone has
ideas for a best approach to specifying a line wrap width
(breaking between words for lines no longer than a specific
column width) for output from a Ruby script, I'd love to
hear about it."

X = 40
puts str.gsub(/\n/," ").scan(/\S.{0,#{X-2}}\S(?=\s|$)|\S+/)