Created
November 8, 2019 21:47
-
-
Save amirrajan/d8ccd9634c2d3eb3cbdb85d36609a2be to your computer and use it in GitHub Desktop.
DragonRuby `String#wrap`
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
class String | |
def wrapped_lines_recur word, rest, length, aggregate | |
if word.nil? | |
return aggregate | |
elsif rest[0].nil? | |
aggregate << word + "\n" | |
return aggregate | |
elsif (word + " " + rest[0]).length > length | |
aggregate << word + "\n" | |
return wrapped_lines_recur rest[0], rest[1..-1], length, aggregate | |
elsif (word + " " + rest[0]).length <= length | |
next_word = (word + " " + rest[0]) | |
return wrapped_lines_recur next_word, rest[1..-1], length, aggregate | |
else | |
log <<-S | |
WARNING: | |
#{word} is too long to fit in length of #{length}. | |
S | |
next_word = (word + " " + rest[0]) | |
return wrapped_lines_recur next_word, rest[1..-1], length, aggregate | |
end | |
end | |
def wrapped_lines length | |
self.each_line.map do |l| | |
l = l.rstrip | |
if l.length < length | |
l + "\n" | |
else | |
words = l.split ' ' | |
wrapped_lines_recur(words[0], words[1..-1], length, []).flatten | |
end | |
end.flatten | |
end | |
def wrap length | |
wrapped_lines(length).join.rstrip | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment