Created
September 1, 2012 17:39
-
-
Save florian/3581285 to your computer and use it in GitHub Desktop.
String#word_wrap for Ruby
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
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 |
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 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