我一直在使用下面的代码来使用 Ruby 查找字符串中给定单词的频率。我的问题是如何调整它以在给定时间找到 2 个单词的频率。例如:“咩咩咩黑羊”应该返回......
{"baa baa"=>2, "baa black"=>1, "black sheep"=>1}
代码:
def count_words(string)
words = string.split(' ')
frequency = Hash.new(0)
words.each { |word| frequency[word.downcase] += 1 }
return frequency
end