0

有人知道,为什么下面的代码会返回错误:

stock = {"M9788375085969"=>5, "M9788392289760"=>5, "M9788389371461"=>1, "M9788389371447"=>3, "M9788392289761"=>2}
add = {"M9788375085969"=>1, "M9788392289760"=>2, "NEW9788392289753"=>1 }

add.each do |key, value|
  stock[key] += value
end

NoMethodError: undefined method `+' for nil:NilClass

虽然类似的事情很好:

key = "M9788375085969"
value = 1
stock[key] += value
=> 6
4

4 回答 4

3

add您的哈希中缺少一个键stock:“NEW9788392289753”。

执行时stock["NEW9788392289753"]nil返回,因为键未映射。

于 2013-11-08T14:38:26.660 回答
2

密钥"NEW9788392289753"不存在于哈希stock中,但存在于add哈希中。见下文 :

stock = {"M9788375085969"=>5, "M9788392289760"=>5, "M9788389371461"=>1, "M9788389371447"=>3, "M9788392289761"=>2}
stock['NEW9788392289753'] # => nil
nil.respond_to?(:+) # => false # means NilClass don't has method called :+

从而nil.+(value)抛出一个有效的错误。执行以下操作:

stock = {"M9788375085969"=>5, "M9788392289760"=>5, "M9788389371461"=>1, "M9788389371447"=>3, "M9788392289761"=>2}
add = {"M9788375085969"=>1, "M9788392289760"=>2, "NEW9788392289753"=>1 }

add.each do |key, value|
  p stock[key] += value if stock.has_key?(key) # it will take care of the error.
end

输出

6
7

根据OP的评论,我会这样做:

add.each do |key, value|
  if stock.has_key?(key) 
     stock[key] += value 
  else
     stock[key] = value
  end
end
于 2013-11-08T14:38:09.397 回答
2

因为NEW9788392289753来自的密钥add不包含在stock.

于 2013-11-08T14:39:30.430 回答
1

处理不存在的键的另一种方法是提供默认值为零:

stock = {"M9788375085969"=>5, "M9788392289760"=>5, "M9788389371461"=>1, "M9788389371447"=>3, "M9788392289761"=>2}
add = {"M9788375085969"=>1, "M9788392289760"=>2, "NEW9788392289753"=>1 }

stock.default = 0 

add.each do |key, value|
  stock[key] += value
end

p stock #=> {"M9788375085969"=>6, "M9788392289760"=>7, "M9788389371461"=>1, "M9788389371447"=>3, "M9788392289761"=>2, "NEW9788392289753"=>1}
于 2013-11-08T16:16:54.313 回答