在过去 45 分钟左右的时间里,我一直在进行这个 Codeacademy 练习。问答论坛提出的解决方案均无效。代码如下。
puts "Type something profound please"
text = gets.chomp
words = text.split
frequencies = Hash.new 0
frequencies = frequencies.sort_by {|x,y| y}
words.each {|word| frequencies[word] += 1}
frequencies = frequencies.sort_by{|x,y| y}.reverse
puts word +" " + frequencies.to_s
frequencies.each do |word, frequencies|
end
为什么不能将字符串转换为整数?我做错了什么?
最佳答案
sort_by { |obj| block } → array
很清楚。
frequencies.sort_by {|x,y| y}
给你一个数组。 frequencies
是一个数组,而不是哈希。因此在 words.each {|word| frequencies[word] += 1}
, frequencies[word]
引发异常,如 frequencies
是一个数组,数组的元素是通过整数索引访问的,但您尝试使用 string word
。 words = text.split
,所以words
保存字符串数组。
关于ruby - 试图理解为什么它不能 "convert string to integer"(Ruby 直方图迭代哈希),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21863662/