Created
October 14, 2012 19:12
-
-
Save jschank/3889529 to your computer and use it in GitHub Desktop.
Text wrapping method
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 wrap_text(text, width, indent_width) | |
raise ArgumentError.new("Width must be at least 1 character wide.") if width <= 1 | |
raise ArgumentError.new("Wrapping width must be greater than the indent amount.") if width <= indent_width | |
width -= indent_width | |
lines = [] | |
curline = nil | |
text.split.each do |word| | |
if (curline == nil) | |
# start a new line | |
curline = "" | |
curline << word << " " | |
elsif (curline.length + word.length <= width) | |
# add the word to the line we're building | |
curline << word << " " | |
else | |
lines << curline | |
curline = nil | |
redo | |
end | |
end | |
lines << curline if curline | |
lines.join("\n") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment