[英]Ruby: NoMethodError: undefined method `+' for nil:NilClass
Would anybody have an idea, why following code returns error: 任何人都有一个主意,为什么以下代码返回错误:
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
while similar thing works fine: 虽然类似的东西可以正常工作:
key = "M9788375085969"
value = 1
stock[key] += value
=> 6
There is one key in your add
hash that is missing in your stock
hash : "NEW9788392289753". 您的stock
哈希中缺少add
哈希中的一个键:“ NEW9788392289753”。
When executing stock["NEW9788392289753"]
, nil
is returned, as the key is not mapped. 执行stock["NEW9788392289753"]
,由于未映射键,因此返回nil
。
The key "NEW9788392289753"
is not present in the Hash stock
,but present in add
hash. 关键的"NEW9788392289753"
是不存在的哈希stock
,但目前在add
哈希值。 See below : 见下文 :
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 :+
Thus nil.+(value)
throwing a valid error. 因此nil.+(value)
抛出有效错误。 Do as below : 执行以下操作:
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
output 输出
6
7
As per OP's comment I would do as : 根据OP的评论,我将这样做:
add.each do |key, value|
if stock.has_key?(key)
stock[key] += value
else
stock[key] = value
end
end
因为add
的密钥NEW9788392289753
不包含在stock
。
Another way of treating non-existent keys is providing a default of zero: 处理不存在的密钥的另一种方法是提供默认值零:
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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.