0

我收到一个错误,即 nil:NilClass 未定义“+”。我假设这是在

index[word] += 1

但不知道为什么。我正在使用 1.9.3。

如果有人可以提供帮助,将不胜感激!谢谢

def most_common_words(text)
text_split = text.split(' ')
index = {}
text_split.each do |word| 
    puts index
    puts word
    if (index[word]
        index[word] += 1 )
    else(
        index[word] = 1 )
    end
end
index.to_a.sort[0..2]
4

2 回答 2

1

评论几乎不正确。

它忽略了实际问题,即您的if语句格式错误。

如果您修复语法,则代码将按原样工作:

index = {}
%w[ohai kthx ohai].each do |word|
  if index[word]
    index[word] += 1
  else
    index[word] = 1
  end
end
puts index.inspect
=> {"ohai"=>2, "kthx"=>1}

或者您可以只提供一个默认值:

index2 = Hash.new(0)
%w[ohai kthx ohai].each do |word|
  index2[word] += 1
end
puts index2.inspect
=> {"ohai"=>2, "kthx"=>1}
于 2013-06-14T19:55:54.980 回答
0

您应该能够将此代码简化为更少的行。它会让它看起来更漂亮、更干净。

    def most_common_words(text)
      text_split = text.split(' ')
      index = Hash.new(1)
      text_split.each do |key, value|
        puts "The key is #{key} and the value is #{value}"
        index[key] += 1
      end
    end
    index.to_a.sort[0..2]
于 2013-06-14T19:56:10.043 回答