Skip to content

Instantly share code, notes, and snippets.

@mahemoff
Created July 25, 2012 00:56
Show Gist options
  • Save mahemoff/3173700 to your computer and use it in GitHub Desktop.
Save mahemoff/3173700 to your computer and use it in GitHub Desktop.
split_lines.rb
# 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