Skip to content

Instantly share code, notes, and snippets.

@sstephenson
Created May 29, 2017 16:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sstephenson/da15ab77db138252192cf740f1b5eee5 to your computer and use it in GitHub Desktop.
Save sstephenson/da15ab77db138252192cf740f1b5eee5 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# Usage: tweetsplit.rb < tweetstorm.txt
# https://twitter.com/CoralineAda/status/869204799027372032
# Sam Stephenson / 2017-05-29
# Tweet-sized version:
# puts $<.read.split(/\s+/).reduce(nil){|(*cs,c),w|n=[c,w].compact*" ";cs+(n.size>140?[c,w]:[n])}*"\n"
def chunks_for(words, chunk_size)
words.reduce([nil]) do |(*chunks, chunk), word|
chunks + next_chunk(chunk_size, chunk, word)
end
end
def next_chunk(chunk_size, chunk, word)
candidate = [chunk, word].compact.join(" ")
if candidate.size > chunk_size
[chunk, word]
else
[candidate]
end
end
puts chunks_for($<.read.split(/\s+/), 140).join("\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment