Skip to content

Instantly share code, notes, and snippets.

@manuelp
Created May 30, 2012 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manuelp/2837619 to your computer and use it in GitHub Desktop.
Save manuelp/2837619 to your computer and use it in GitHub Desktop.
Word wrap in Ruby
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