Method to WRAP text at _ # of characters?

Made myself a li’l Ruby class for sending email.

But of course I’d like to wrap the outgoing body of text at
68 characters or so, before sending.

Having taken PHP’s “wordwrap” function for granted,
(http://us2.php.net/wordwrap), I was surprised not to find
a similar method built-in to Ruby.

Or is it?
Did I miss it?
Am I going to have to write my own?

Try searching for “gsub \1 \n” in the comp.lang.ruby search bar at
http://www.rubyforge.org. The first result is a discussion about a wrap
method.

···

On Sun, Feb 15, 2004 at 04:11:36PM +0900, Ruby Baby wrote:

Made myself a li’l Ruby class for sending email.

But of course I’d like to wrap the outgoing body of text at
68 characters or so, before sending.

Having taken PHP’s “wordwrap” function for granted,
(http://us2.php.net/wordwrap), I was surprised not to find
a similar method built-in to Ruby.

Or is it?
Did I miss it?
Am I going to have to write my own?


Zachary P. Landau kapheine@hypa.net
GPG: gpg --recv-key 0x24E5AD99 | http://kapheine.hypa.net/kapheine.asc

Ruby Baby wrote:

Having taken PHP’s “wordwrap” function for granted,
(http://us2.php.net/wordwrap), I was surprised not to find
a similar method built-in to Ruby.

Here’s a simple one I like to use:

Wrapping strings for display

class String
def wordwrap( len )
gsub( /\n/, “\n\n” ).gsub( /(.{1,#{len}})(\s+|$)/, “\1\n” )
end
end

s = “Insert unwrapped and elaborate, exhaustive tomes here.”
s.wordwrap( 68 )
#=> outputs string wrapped to 68 columns

However, the String#wordwrap method is rather limited, so if I ever end
up needing something more, I use the Text::Format[1] module.

require ‘text/format’

formatter = Text::Format.new {
@columns = 68
@first_indent = 0
}

s = “Insert unwrapped and elaborate, exhaustive tomes here.”
formatter.format( s )

Yip.

_why

[1] http://raa.ruby-lang.org/list.rhtml?name=text-format

There’s a wrap implementation in ‘rough’ (a CVS repository of
candiates for the Ruby standard library), as well as a few other text
manipulation things. I’d like to see them all become standard,
although better organised than they are now.

Gavin

···

On Sunday, February 15, 2004, 6:11:36 PM, Ruby wrote:

Made myself a li’l Ruby class for sending email.

But of course I’d like to wrap the outgoing body of text at
68 characters or so, before sending.

Having taken PHP’s “wordwrap” function for granted,
(http://us2.php.net/wordwrap), I was surprised not to find
a similar method built-in to Ruby.

Or is it?
Did I miss it?
Am I going to have to write my own?