我以为我可以增加ruby中哈希键的值.为什么这会失败?

lam*_*ade 2 ruby

hash = {"bill"=>'39','kim'=>'35','larry'=>'47'}

哈希哈希[word] + = 1结束的单词

把"比尔现在#{hash ['bill]']}"

这是错误消息

未定义的方法`+'表示nil:NilClass(NoMethodError)

jer*_*ith 6

这不起作用,因为word它将表示散列中每个键/值对的数组.所以,在第一次通过循环时,word将是["bill", "39"].这hash[word]就是回归的原因nil.

图说:

ruby-1.9.2-p180 :001 > for word in hash
ruby-1.9.2-p180 :002?>   puts word.inspect
ruby-1.9.2-p180 :003?> end
["bill", 40]
["kim", 36]
["larry", 48]
Run Code Online (Sandbox Code Playgroud)

你可能想要的是:

hash.keys.each do |k|
  hash[k] += 1
end
Run Code Online (Sandbox Code Playgroud)

第二个问题是您将值存储为字符串而不是Ints.因此,+ = 1操作将失败.将哈希值更改为:

hash = { "bill" => 39, 'kim' => 35, 'larry' => 47 }
Run Code Online (Sandbox Code Playgroud)

或者在执行+ 1之前将值转换为整数.