Skip to content

Instantly share code, notes, and snippets.

@krishicks
Last active December 11, 2015 21:19
Show Gist options
  • Save krishicks/4661630 to your computer and use it in GitHub Desktop.
Save krishicks/4661630 to your computer and use it in GitHub Desktop.
chunkify
def chunkify enum, out, limit, &block
enum.inject([]) do |acc, e|
size = (acc+[e]).join(",").size
if size > limit
out += yield(acc)
acc = [e]
elsif e == enum.last
out += yield(acc + [e])
else
acc << e
end
end
out
end
def word_wrap string, length
chunkify(string.split(/\s/), "", length) { |a| a.join(" ") + "\n" }
end
str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
ww_str = word_wrap str, 80
ww_str.split("\n").map &:size
# => [79, 74, 77, 79, 78, 54]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment