WuyaSea Operator wrote:
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.
"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.
--
Paul Lutus
http://www.arachnoid.com