Skip to content

Instantly share code, notes, and snippets.

@hrp
Created May 28, 2013 22:15
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 hrp/5666577 to your computer and use it in GitHub Desktop.
Save hrp/5666577 to your computer and use it in GitHub Desktop.
WJ's homework.
require './string'
describe "String#condensify" do
it "encodes a string" do
input = "AAASSSDDDDRDDSASSDDDSSSAD"
output = "3A3S4DR2DSA2S3D3SAD"
input.condensify.should == output
end
it "encodes a string with no repeats" do
input = "ABCDEFG"
input.condensify.should == input
end
end
class String
def condensify
split_by_repeating.map! do |item|
if item.length > 1
"#{item.length}#{item[0]}"
else
item
end
end.join
end
def split_by_repeating
hero = []
self.each_char do |char|
if hero.last && hero.last[0] == char
hero[hero.length-1] = hero.last + char
else
hero << char
end
end
hero
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment