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

时间:2011-11-02 21:02:05

标签: ruby

  

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

     

for hash hash [word] + = 1 end

     

将“Bill现在#{hash ['bill]']}”

这是错误消息

  

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

3 个答案:

答案 0 :(得分: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]

你可能想要的是:

hash.keys.each do |k|
  hash[k] += 1
end

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

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

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

答案 1 :(得分:2)

您需要在for for循环中为散列指定2个变量:

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

for word, key in hash 
  hash[word] += 1 
end

puts "Bill is now #{hash['bill]'}"

答案 2 :(得分:1)

您应该使用原生 each枚举器:

friend_ages = { 'Bill' => 39, 'Kim' => 35, 'Larry' => 47 }
friend_ages.each { |name, age| friend_ages[name] += 1 }

puts "Bill is now #{friend_ages['Bill']}."