Skip to content

Instantly share code, notes, and snippets.

@ma11hew28
Created April 2, 2011 14:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ma11hew28/899520 to your computer and use it in GitHub Desktop.
Save ma11hew28/899520 to your computer and use it in GitHub Desktop.
String#reverse_words & #longest_run
require 'rspec'
class String
if method_defined? :reverse_words
raise "String#reverse_words is already defined"
end
def reverse_words
split(' ').reverse!.join(' ')
end
if method_defined? :longest_run
raise "String#longest_run is already defined"
end
def longest_run
return 0 if empty?
max_count = 1
tmp_count = 1
tmp_char = nil # previous character
each_char do |c|
if tmp_char == c
tmp_count += 1
max_count = [max_count, tmp_count].max
else
tmp_count = 1
end
tmp_char = c
end
max_count
end
end
describe String do
describe "#reverse_words" do
# specify { "hello".reverse_words.should eq("hello") }
# specify { "hello world".reverse_words.should eq("world hello") }
# specify { "bob & pop run".reverse_words.should eq("run pop & bob") }
strings = {
"hello" => "hello",
"hello world" => "world hello",
"bob & pop run" => "run pop & bob"
}
strings.each do |k, v|
specify "\"#{k}\" => \"#{v}\"" do
k.reverse_words.should eq(v)
end
end
end
describe "#longest_run" do
# specify { "".longest_run.should equal(0) }
# specify { "a".longest_run.should equal(1) }
# specify { "ab".longest_run.should equal(1) }
# specify { "aab".longest_run.should equal(2) }
# specify { "abbbaabb".longest_run.should equal(3) }
strings = {
"" => 0,
"a" => 1,
"ab" => 1,
"abb" => 2,
"abbbaabb" => 3
}
strings.each do |k, v|
specify "\"#{k}\" => \"#{v}\"" do
k.longest_run.should equal(v)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment