Created
July 25, 2012 00:56
-
-
Save mahemoff/3173700 to your computer and use it in GitHub Desktop.
split_lines.rb
This file contains hidden or 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
# A word splitting algorithm optimised for laying out arbitrary text into a fixed-width, variable-height, space. | |
# | |
# Splits the string into lines, where each line is smaller than some MAX characters (related to the width of the space). | |
# If the first word is longer than MAX, it is *not* split, but becomes the entire line. | |
# The algorithm isn't (yet) smart enough to try balancing the length of each line. To compensate for this, it tries to avoid | |
# the naieve situation where the bottom line ends up being a few remainder characters, simply by reversing the order it | |
# processes the string. So if anything's likely to be unbalanced, it's the top line that will be small instead of the bottom line. | |
# walks through the string in reverse so as to end up with a longer string at the end. | |
# | |
# Caveat: Needs more testing | |
class String | |
def split_lines(max_chars=20) | |
lines = [] | |
current_line = '' | |
self.split.reverse.each_with_index { |word,i| | |
if (current_line.length + word.length > max_chars) | |
lines.push current_line | |
current_line = '' | |
end | |
current_line+=(current_line.empty? ? '' : ' ') + word | |
if i==self.split.length-1 and !current_line.empty? # last line | |
lines.push current_line | |
end | |
} | |
lines.reverse.map { |line| line.split.reverse.join(' ') } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment