Skip to content

Instantly share code, notes, and snippets.

@florian
Created September 1, 2012 17:39
Show Gist options
  • Save florian/3581285 to your computer and use it in GitHub Desktop.
Save florian/3581285 to your computer and use it in GitHub Desktop.
String#word_wrap for Ruby
text = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam"
puts text.word_wrap(40)
# Lorem ipsum dolor sit amet, consetetur
# sadipscing elitr, sed diam nonumy eirmod
# tempor invidunt ut labore et dolore
# magna aliquyam
class String
def word_wrap n
words = self.split ' '
str = words.shift
words.each do |word|
connection = (str.size - str.rindex("\n").to_i + word.size > n) ? "\n" : " "
str += connection + word
end
str
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment