我目前正在爲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
什麼是正則表達式,包括撇號?
更新了您的反饋意見的問題。謝謝。 – LMo
這工作:splitted = input.downcase.scan(/ [\ w'] + /) – LMo
正確的,這就是我所建議的,模數大寫錯別字。 :-) –