2012-02-25 18 views
-4

我有一個關於Ruby的問題:伯爵的話沒有循環

給定的輸入字符串,我需要返回一個哈希,它的鍵是單詞的字符串,其值的時候出現的每個字的數量。重要提示:我不能使用for循環。輸出:{'今日'=> 1,'是'=> 1,'a'=> 2,'日'=> 1,'日出' => 1}

你能幫我嗎?

+2

聽起來像它,否則爲什麼'for'循環約束? – DNA 2012-02-25 22:20:48

回答

0

如果您有for循環約束,請進行遞歸!
只是不要忘記有停止條件。

+0

map/reduce在這裏可能更好,並且可以在多核計算機上做得很好 – 2012-10-01 09:40:35

5

嘗試是這樣的:

def count_words_without_loops(string) 
    res = Hash.new(0) 
    string.downcase.scan(/\w+/).map{|word| res[word] = string.downcase.scan(/\b#{word}\b/).size} 
    return res 
end 
5
h = Hash.new(0) 
"Today is a day, a sunrise".scan(/\w+/) do |w| 
    h[w] += 1 
end 

p h # {"Today"=>1, "is"=>1, "a"=>2, "day"=>1, "sunrise"=>1} 
+0

尼斯:)。如果OP需要它,那麼.downcase可能會擠在那裏。 – 2012-10-01 09:39:48