Skip to content

Instantly share code, notes, and snippets.

@agmcleod
Created January 3, 2012 22:09
Show Gist options
  • Save agmcleod/1557202 to your computer and use it in GitHub Desktop.
Save agmcleod/1557202 to your computer and use it in GitHub Desktop.
ruby kata, word wrap
class Wrapper
def self.wrap(string, column_to_wrap)
recursive_wrap(string.reverse.scan(/\S+\s?/), column_to_wrap).reverse
end
def self.recursive_wrap(array, column)
head = array[0]
if head.scan(/.{1,#{column}}/).length > 1
head = head.strip.reverse.scan(/.{1,#{column}}/).collect{ |c| c.reverse }.reverse.join("\n")
end
# remove trailing space on last word
return head.strip if array.length == 1
remainder = recursive_wrap(array[1..-1], column)
line_length = remainder.index("\n") || remainder.length
delimiter = head[-1]
if line_length + head.length > column
head.strip + "\n" + remainder
else
head.strip + delimiter + remainder
end
end
end
require 'rspec'
require '../lib/wrapper.rb'
describe Wrapper do
describe "::wrap" do
subject { Wrapper::wrap(string, column_length) }
let(:string) { "somestring" }
let(:column_length) { 5 }
its(:class) { should == String}
context "line length < column" do
let(:column_length) { 99 }
it { should == string }
end
context "line length > column" do
let(:string) { "my test string" }
let(:column_length) { 9 }
it { should include "\n" }
end
context "line is 3 times longer than max length" do
let(:string) { "the the the" }
let(:column_length) { 4 }
specify do
subject.split(/\n/).length.should == 3
end
it { should == "the\nthe\nthe" }
end
context "word length > column length" do
let(:string) { "aaaaa" }
let(:column_length) { 3 }
it { should == "aaa\naa" }
context "with existing words" do
let(:string) { "a aaaaa" }
it { should == "a\naaa\naa"}
end
context "with a few words" do
let(:string) { "aa aa aa" }
let(:column_length) { 5 }
it { should == "aa aa\naa" }
end
context "with periods" do
let(:string) { "aa.bb.cc." }
it { should == "aa.\nbb.\ncc." }
end
context "with tabs" do
let(:string) { "a\tb\tc" }
let(:column_length) { 3 }
it { should == "a\tb\nc" }
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment