Michael Fellinger
12/11/2006 6:58:00 AM
On Monday 11 December 2006 14:20, 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.
>
It's not perfect, but well... just inviting all the regex-gurus to improve
it ;)
^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"]
> operator
> www.wuyaSea.com