【发布时间】:2014-03-16 07:51:14
【问题描述】:
对于我正在处理的一项作业,我正在尝试按文本中单词的频率对一段文本中的单词进行排序。我有一个几乎可以完成我想做但不完全的功能。以下是我的代码:
require 'pry'
def top_words(words)
word_count = Hash.new(0)
words = words.split(" ")
words.each { |word| word_count[word] += 1 }
word_count = word_count.sort_by do |words, frequencies|
frequencies
end
binding.pry
word_count.reverse!
word_count.each { |word, frequencies| puts word + " " + frequencies.to_s }
end
words = "1st RULE: You do not talk about FIGHT CLUB.
2nd RULE: You DO NOT talk about FIGHT CLUB.
3rd RULE: If someone says 'stop' or goes limp, taps out the fight is over.
4th RULE: Only two guys to a fight.
5th RULE: One fight at a time.
6th RULE: No shirts, no shoes.
7th RULE: Fights will go on as long as they have to.
8th RULE: If this is your first night at FIGHT CLUB, you HAVE to fight."
由于某种原因,我的 binding.pry 上面的 sort_by 方法正在将我的 Hash 的结构更改为数组的数组。为什么? 我想做的是对哈希中的单词进行排序,然后从哈希中获取前三个单词。我还没有弄清楚如何做到这一点,但我很确定一旦我对数组问题的数组进行了排序,我就可以做到这一点。
现在,我想我可以使用 .each 和 array[0].each { |stuff| 来获取它们puts stuff[0] + stuff[1] } 但我认为这不是最有效的方法。有什么建议吗?
【问题讨论】: