Skip to content

Instantly share code, notes, and snippets.

@prehnRA
Last active October 30, 2015 18:12
Show Gist options
  • Save prehnRA/c4841c46dbed020ad4c8 to your computer and use it in GitHub Desktop.
Save prehnRA/c4841c46dbed020ad4c8 to your computer and use it in GitHub Desktop.
# Write a method called `word_wrap` that takes 1 to 2 arguments.
# The first argument is a string.
# The second argument is optional, and represents a maximum line length. The
# default value should be 80.
# `word_wrap` should a string formatted such that no line is longer than the
# line length specified by the second argument (i.e. no more than N characters
# between newlines).
# You should not break words apart, however, you can assume that the line width
# will never be shorter than the longest word.
def word_wrap(text, line_width = 80)
text.split("\n").map do |line|
if line.length > line_width
line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1\n").strip
else
line
end
end * "\n"
end
# BEGIN TEST CASES
TEST_CASES = {"It is an ancient Mariner,\nAnd he stoppeth one of three.\n\"By thy long beard and glittering eye,\nNow wherefore stopp'st thou me?"=>{20=>"It is an ancient\nMariner,\nAnd he stoppeth one\nof three.\n\"By thy long beard\nand glittering eye,\nNow wherefore\nstopp'st thou me?", 40=>"It is an ancient Mariner,\nAnd he stoppeth one of three.\n\"By thy long beard and glittering eye,\nNow wherefore stopp'st thou me?", 60=>"It is an ancient Mariner,\nAnd he stoppeth one of three.\n\"By thy long beard and glittering eye,\nNow wherefore stopp'st thou me?"}, "I find myself alone these days, more often than not, watching the rain run down nearby windows. How long has it been raining? The newspapers now print the total, but no one reads them anymore."=>{20=>"I find myself alone\nthese days, more\noften than not,\nwatching the rain\nrun down nearby\nwindows. How long\nhas it been raining?\nThe newspapers now\nprint the total, but\nno one reads them\nanymore.", 40=>"I find myself alone these days, more\noften than not, watching the rain run\ndown nearby windows. How long has it\nbeen raining? The newspapers now print\nthe total, but no one reads them\nanymore.", 60=>"I find myself alone these days, more often than not,\nwatching the rain run down nearby windows. How long has it\nbeen raining? The newspapers now print the total, but no one\nreads them anymore."}}
def test
test_results = TEST_CASES.each_with_object({failures: 0}) do |pair, test_results|
original_string, cases = pair
cases.each do |width, result|
next if word_wrap(original_string, width) == result
puts "Failed. Trying to wrap to #{width} characters:"
puts original_string
puts ""
puts "Expected:"
puts result
puts "----"
puts "Got:"
puts word_wrap(original_string, width)
puts "========================="
puts "\n"*3
test_results[:failures] += 1
end
end
puts "#{test_results[:failures]} failed cases."
end
test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment