wordfrequency = Hash.new(0)
splitfed.each { |word| wordfrequency[word] += 1 }

wordfrequency = wordfrequency.sort_by {|x,y| y }
wordfrequency.reverse!

puts wordfrequency

我已经将这些单词添加到一个哈希表中,并让它按单词频率排序,但是当我希望它按字母顺序排列时,每个频率内的顺序都是随机的。有什么速效药吗?谢谢!非常感谢。

最佳答案

您可以使用:

wordfrequency = wordfrequency.sort_by{|x,y| [y, x] }

按值然后按键排序。
对你来说,
splitfed = ["bye", "hi", "hi", "a", "a", "there", "alphabet"]


wordfrequency = Hash.new(0)
splitfed.each { |word| wordfrequency[word] += 1 }

wordfrequency = wordfrequency.sort_by{|x,y| [y, x] }
wordfrequency.reverse!

puts wordfrequency.inspect

将输出:
[["hi", 2], ["a", 2], ["there", 1], ["bye", 1], ["alphabet", 1]]

这个词的出现顺序与这个词本身的出现顺序相反。
确保您注意到(这可能很明显)wordfrequency现在是一个数组。

10-05 22:09