Created
November 28, 2012 17:10
-
-
Save kristenmills/4162590 to your computer and use it in GitHub Desktop.
Splits a string into lines so that the number characters in a line is less than or equal to a specified length. Individual words will only be split if the word itself has more characters than can fit on a line.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def split string, length | |
split = Array.new | |
if string.length > length #if the string needs to be split | |
string_words = string.split(" ") | |
line = "" | |
string_words.each do |x| | |
if x.length > length #if the word needs to be split | |
#add the start of the word onto the first line (even if it has already started) | |
while line.length < length | |
line += x[0] | |
x = x[1..-1] | |
end | |
split << line | |
#split the rest of the word up onto new lines | |
split_word = x.scan(%r[.{1,#{length}}]) | |
split_word[0..-2].each do |word| | |
split << word | |
end | |
line = split_word.last+" " | |
elsif (line + x).length > length-1 #if the word would fit alone on its own line | |
split << line.chomp | |
line = x + " " | |
else #if the word can be added to this line | |
line += x + " " | |
end | |
end | |
split << line | |
else #if the string doesn't need to be split | |
split = [string] | |
end | |
#give back the split line | |
return split | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment