2013-12-11 96 views
1

我目前正在爲Ruby做一個練習,並且無法通過最後的測試。最後一次測試讀取:什麼是包含撇號的Ruby正則表達式?

def test_with_apostrophes 
    phrase = Phrase.new("First: don't laugh. Then: don't cry.") 
    counts = {"first"=>1, "don't"=>2, "laugh"=>1, "then"=>1, "cry"=>1} 
    assert_equal counts, phrase.word_count 
end 

錯誤我收到的是:

1) Failure: 
PhraseTest#test_with_apostrophes [word_count_test.rb:61]: 
--- expected 
+++ actual 
@@ -1 +1 @@ 
-{"first"=>1, "don't"=>2, "laugh"=>1, "then"=>1, "cry"=>1} 
+{"first"=>1, "don"=>2, "t"=>2, "laugh"=>1, "then"=>1, "cry"=>1} 

我當前的代碼是:

class Phrase 
    attr_reader :input 

    def initialize(input) 
    @input = input 
    end 

    def word_count 
    count = {} 
    splitted = input.downcase.scan(/\w+/) 
    splitted.each do | word | 
    if !count.key?(word) 
    count[word] = 1 
    else 
    count[word] = count[word] + 1 
    end 
    end 
    count 
end 
end 

什麼是正則表達式,包括撇號?

回答

3

您想要使用「字符類」,如http://www.regular-expressions.info/charclass.html中所述。

所以,與其\w+,您可以使用[\w']+,它說你想要一個或多個要麼單詞字符或撇號。

+0

更新了您的反饋意見的問題。謝謝。 – LMo

+0

這工作:splitted = input.downcase.scan(/ [\ w'] + /) – LMo

+0

正確的,這就是我所建議的,模數大寫錯別字。 :-) –

1

嘗試:

splitted = input.downcase.scan(/[\w-']+/) 
1

試試這個讓你的話的頻率,

words_freq = Hash.new(0) 

"First: don't laugh. Then: don't cry.".split(/\s+/).each { |word| words_freq[word.downcase.delete(':|.')] += 1 } 

#words_freq = {"first"=>1, "don't"=>2, "laugh"=>1, "then"=>1, "cry"=>1}

+0

這不會出於幾個原因。首先,冒號在匹配的單詞中。其次,'words_freq'中的鍵有大寫字母。 –

+0

注意和糾正! – eastafri

相關問題