Created
May 30, 2012 16:58
-
-
Save manuelp/2837619 to your computer and use it in GitHub Desktop.
Word wrap in 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
class WordWrap | |
def initialize(text) | |
@text = text | |
end | |
def wrap(col) | |
result = "" | |
len = 0 | |
@text.split(" ").each do |word| | |
if (len + word.length + 1) <= col then | |
result += " " + word | |
len += word.length + 1 | |
else | |
result += "\n" + word | |
len = word.length + 1 | |
end | |
end | |
result | |
end | |
end | |
col = 50 | |
text = "The path of the righteous man is beset on all sides by the iniquities of the selfish and the tyranny of evil men. Blessed is he who, in the name of charity and good will, shepherds the weak through the valley of darkness, for he is truly his brother's keeper and the finder of lost children. And I will strike down upon thee with great vengeance and furious anger those who would attempt to poison and destroy My brothers. And you will know My name is the Lord when I lay My vengeance upon thee." | |
qualcosa = WordWrap.new(text) | |
wrapped = qualcosa.wrap(col) | |
puts wrapped | |
puts "-" * col |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment