Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100755 56 lines (43 sloc) 1.415 kb
8a5667d @kerryb Fixed typos. Tests pass.
authored
1 #!/usr/bin/env ruby
a1a35ec @kerryb
authored
2 #
3 #See http://blogs.agilefaqs.com/2009/07/08/refactoring-teaser-part-1/
4
8a5667d @kerryb Fixed typos. Tests pass.
authored
5 require 'spec'
6
50d68c2 @kerryb First attempt at porting to Ruby
authored
7 module StringExtensions
8a5667d @kerryb Fixed typos. Tests pass.
authored
8 def phrases(number)
e6cba04 @kerryb rename strings to words
authored
9 words = split
04b2a46 @kerryb No need to calculate single words when we already have them
authored
10 all_strings = words
d5ab509 @kerryb Separate methods for two- and three-word phrases
authored
11 all_strings += double_words(words)
12 all_strings += triple_words(words)
45d5728 @kerryb Simplified building of result string
authored
13 all_strings[0, number].map {|s| "'#{s}'"}.join(', ')
8a5667d @kerryb Fixed typos. Tests pass.
authored
14 end
15
16 private
a1a35ec @kerryb
authored
17
d5ab509 @kerryb Separate methods for two- and three-word phrases
authored
18 def double_words(strings)
813d40d @kerryb Extract general method to find n-word phrases
authored
19 extract_phrases(strings, 2)
d5ab509 @kerryb Separate methods for two- and three-word phrases
authored
20 end
21
22 def triple_words(strings)
813d40d @kerryb Extract general method to find n-word phrases
authored
23 extract_phrases(strings, 3)
24 end
25
26 def extract_phrases(strings, number_of_words)
27 result = []
28 (0...strings.size - number_of_words + 1).each do |i|
29 phrase = strings[i, number_of_words].join(' ')
30 result << phrase
8a5667d @kerryb Fixed typos. Tests pass.
authored
31 end
813d40d @kerryb Extract general method to find n-word phrases
authored
32 result
8a5667d @kerryb Fixed typos. Tests pass.
authored
33 end
50d68c2 @kerryb First attempt at porting to Ruby
authored
34 end
35
36 String.send(:include, StringExtensions)
37
38 describe StringExtensions do
39 it 'finds all phrases' do
40 'Hello World Ruby'.phrases(6).should == "'Hello', 'World', 'Ruby', 'Hello World', 'World Ruby', 'Hello World Ruby'"
41 end
42
43 it 'returns all phrases when asked for more than exist' do
44 'Hello World Ruby'.phrases(10).should == "'Hello', 'World', 'Ruby', 'Hello World', 'World Ruby', 'Hello World Ruby'"
45 end
46
47 it 'returns the first n phrases when asked for fewer than exist' do
48 'Hello World Ruby'.phrases(4).should == "'Hello', 'World', 'Ruby', 'Hello World'"
49 end
50
51 it 'returns the first word when asked for one phrase' do
52 'Hello World Ruby'.phrases(1).should == "'Hello'"
53 end
54 end
a1a35ec @kerryb
authored
55
Something went wrong with that request. Please try again.