can it be shorter?

W

WuyaSea Operator

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
 
M

Michael Fellinger

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"]
 
J

James Edward Gray II

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.

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

James Edward Gray II
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top