Created
          April 2, 2011 14:17 
        
      - 
      
 - 
        
Save ma11hew28/899520 to your computer and use it in GitHub Desktop.  
    String#reverse_words & #longest_run
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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