Setting string width

Hi there,Just a quick question …
I’d like to insert newlines into a string around every 80ish
character and those newlines shouldnt cut the words in the middle. Can
anybody post a snippet how to do that
TIA
hurcan

Hurcan

The following adds a method to the string class called wrap which wraps
a
string at the specified width broken on a space but honouring line
endings

class String
def wrap(width)
gsub(/(.{1,#{width}})(\s+|\Z)/, “\1\n”)
end
end

s = “Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas
cursus cursus enim. Ut sit amet metus at lacus consectetuer condimentum.
Suspendisse nulla arcu, varius eget, consequat id, sodales sit amet,
turpis.
Etiam ornare felis id augue. Morbi eleifend sem nec odio. Aenean augue
dui,
placerat et, porta tincidunt, accumsan vitae, tortor. Ut et nulla et
diam
gravida eleifend. Nulla fermentum ligula nec tellus. Donec quis purus id
nisl blandit fermentum. Nunc commodo metus sit amet tortor. Nam lacus
quam,
ultricies sit amet, fermentum at, dictum eget, metus.”

puts s.wrap(80)

Andrew T.
[email protected]
082 415 8283
skype: andrewtimberlake

“I have never let my schooling interfere with my education.”
–Mark Twain

From: “hurcan solter” [email protected]

Hi there,Just a quick question …
I’d like to insert newlines into a string around every 80ish
character and those newlines shouldnt cut the words in the middle. Can
anybody post a snippet how to do that

Here’s one way to do it:

string.gsub(/(.{75,}?\S*)\s+/, “\1\n”)

It meets the criteria of “around every 80ish character”… :slight_smile:

Regards,

Bill

From: “Andrew T.” [email protected]

gsub(/(.{1,#{width}})(\s+|\Z)/, “\1\n”)

Ah, nice.

Regards,

Bill

yes yes the word was “the word wrap” .Silly me
thanks for the responses though…

On Jan 14, 2008, at 10:00 AM, hurcan solter wrote:

I’d like to insert newlines into a string around every 80ish
character and those newlines shouldnt cut the words in the middle. Can
anybody post a snippet how to do that

require ‘facets’
str.word_wrap!

On Jan 14, 2008 11:18 AM, Bill K. [email protected] wrote:

From: “Andrew T.” [email protected]

gsub(/(.{1,#{width}})(\s+|\Z)/, “\1\n”)

Ah, nice.

I know you have been served well but I would like to take advantage to
point to a RubyQuiz as there are surprisingly often
answers to Ruby programming questions. Yours was handled here
http://rubyquiz.com/quiz113.html

BTW James, will the Quiz page remain available after your retierement?

Cheers
Robert


Whereof one cannot speak, thereof one must be silent.
Ludwig Wittgenstein

On Jan 14, 2008, at 5:45 AM, Robert D. wrote:

BTW James, will the Quiz page remain available after your retierement?

Absolutely.

James Edward G. II