Ruby:获取错误[]':没有将String隐式转换为Integer(TypeError)

时间:2017-07-04 10:26:46

标签: ruby-on-rails ruby

class LineAnalyzer
    @@highest_wf_count = 0
    @@highest_wf_words = Hash.new(0)

    def initialize(content, line_number)
      @content = content
      @line_number = line_number
      calculate_word_frequency(content)
    end

    def calculate_word_frequency(content)
        content.split.each do |word|
          @@highest_wf_words[word.downcase] +=1
        end
        @@highest_wf_words = @@highest_wf_words.sort_by{|k,v| -v}
    end
end 

class Solution

    def initialize()
        @analyzers = Array.new
        @highest_count_words_across_lines = Array.new
    end
    def analyze_file()
        @line_number = 0
        File.foreach('test.txt') do |content|
          @line_number += 1
          @line = LineAnalyzer.new(content,@line_number)
          @analyzers.<<(@line)
        end
    end    
end

尝试创建LineAnalyzer对象并传递值时,会在以下位置出现此错误:

@line = LineAnalyzer.new(content,@line_number)

这就是我得到的:

Max-Word-Freq/module2_assignment.rb:34:in `calculate_word_frequency'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:25:in `initialize'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:68:in `new'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:68:in `block in analyze_file'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:66:in `foreach'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:66:in `analyze_file'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/solution.rb:10:in `<main>'

1 个答案:

答案 0 :(得分:0)

您出现此错误,因为您尝试使用Array Hash。{。} 在这一行:

 @@highest_wf_words = @@highest_wf_words.sort_by{|k,v| -v}

第一次@@highest_wf_words确实是Hash,但sort_by方法返回Array。因此,当您再次使用它时,您会遇到错误。

如果要按值对哈希值进行排序,可以执行以下操作:

@@highest_wf_words = Hash[@@highest_wf_words.sort]
# Or reverse it
@@highest_wf_words = Hash[@@highest_wf_words.sort.reverse]

请查看此内容以获得进一步说明:Hash::[]