Break Strings into Separate Lines
June 16, 2008, 12:36 pm
Filed under: Uncategorized
Filed under: Uncategorized
I’m working on a site that has a fixed page height and should not scroll. Because of this, the amount of text displayed on a page needs to not exceed a maximum value. I wrote the following function to break a string into lines based on either line breaks, or the amount of characters that can fit across the div.
Ruby 1.9 already has a function to break a string into lines; however, this does not include the option to break up a line based on characters and I am still on Ruby 1.8.6.
def lines s, chars=0
string = s
line_array = Array.new
while(string.size > 0)
i = string.index("\n")
# Takes the string up to either the first line break
line = string.slice!(0..(i || string.size - 1)).chomp
# Breaks the line up into separate lines based on the number of characters
if line.size > chars && chars > 0
while(line.size > chars)
ending = chars - 1
unless line[ending + 1, 1] == " "
ending = line.size - 1 - line.reverse.index(" ", -ending)
end
line_array << line.slice!(0..ending).strip
end
end
line_array << line.strip
end
return line_array
end
Leave a Comment