Can it be shorter?

doing formating, i need to break a long line of words to roughly 80
chars per line, below is what I got

def break_line(text)
return text if text.size < 80

i = text.index(' ', 79)
text[0..i] + "\n" + break_line(text[i+1..-1])

end

can it be any shorter, more rubyish? Thank you.

operator
www.wuyaSea.com

WuyaSea O. wrote:

can it be any shorter, more rubyish? Thank you.

“Shorter” is one issue, but you really don’t need to recurse to
accomplish
your goal, because the recursion technique should not be used where it
is
not needed. It is sometimes a temptation because it looks elegant and
saves
a few lines, but in this specific case, with a lot of text being pushed
onto the stack, it may cause an overflow and terminate your program in
the
field, long after you have forgotten about it.

Also, you don’t want to use “index”, you want to use “rindex”, to find
the
last whitespace counting from the right, not the first whitespace
counting
from the left, which is what your code does.

Finally, test your code with paragraphs that don’t have any spaces in
them
– just long sequences of characters broken by linefeeds. This is a
condition that isn’t likely, but the code should behave itself if this
happens, e.g. not produce lines longer than 80 characters.

Sample code:


#!/usr/bin/ruby -w

def ljust(s,len)
out = “”
begin
p = len
p = s.rindex(/\s/,len) || len if(s.length > len)
out += s[0 … p].strip + “\n”
s = s[p … -1]
end while(s && s.length > 0)
out
end

data = File.read(“sample.txt”)

data.each do |line|
print ljust(line,80)
end


Compare the output of this program with your own, and imagine there’s a
requirement that no line be longer than 80 characters.

On Dec 10, 2006, at 11:20 PM, WuyaSea O. wrote:

can it be any shorter, more rubyish? Thank you.

def break_line(text)
text.gsub!(/(.{1,80}|\S{81,})(?: +|$\n?)/, “\1\n”)
end

James Edward G. II

On Monday 11 December 2006 14:20, WuyaSea O. wrote:

can it be any shorter, more rubyish? Thank you.

It’s not perfect, but well… just inviting all the regex-gurus to
improve
it :wink:

^manveru

class String
def linearize(max = 60)
scan(/.{1,#{max}}(?=\s|$)/)
end
end

“The Lojban alphabet consists of the 26 characters”.linearize

[“The Lojban alphabet consists of the 26 characters”]

“The Lojban alphabet consists of the 26 characters”.linearize 10

[“The Lojban”, " alphabet", " consists", " of the 26", “characters”]

“The Lojban alphabet consists of the 26 characters”.linearize 20

[“The Lojban alphabet”, " consists of the 26", " characters"]

“The Lojban alphabet consists of the 26 characters”.linearize 30

[“The Lojban alphabet consists”, " of the 26 characters"]

“The Lojban alphabet consists of the 26 characters”.linearize 40

[“The Lojban alphabet consists of the 26”, " characters"]