Skip to content

Instantly share code, notes, and snippets.

@amirrajan
Created November 8, 2019 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amirrajan/d8ccd9634c2d3eb3cbdb85d36609a2be to your computer and use it in GitHub Desktop.
Save amirrajan/d8ccd9634c2d3eb3cbdb85d36609a2be to your computer and use it in GitHub Desktop.
DragonRuby `String#wrap`
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