计算没有LOOPS的单词

-4 ruby hash words mapreduce count

我有一个关于Ruby的问题:

给定一个输入字符串,我需要返回一个哈希,其键是字符串中的单词,其值是每个单词出现的次数.重要提示:我不能使用for循环.

示例:"今天是一天,一个日出"输出:{'今天'=> 1,'是'=> 1,'a'=> 2,'天'=> 1,'日出'=> 1}

你能帮助我吗?

Ale*_*Che 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
Run Code Online (Sandbox Code Playgroud)


Sel*_*lug 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}
Run Code Online (Sandbox Code Playgroud)