Reputation: 101
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
Upvotes: 0
Views: 758
Reputation: 118289
The key "NEW9788392289753"
is not present in the Hash stock
,but present in add
hash. 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. 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 :
add.each do |key, value|
if stock.has_key?(key)
stock[key] += value
else
stock[key] = value
end
end
Upvotes: 2
Reputation: 80085
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}
Upvotes: 1
Reputation: 2565
because the key NEW9788392289753
from add
is not contained in stock
.
Upvotes: 2
Reputation: 61578
There is one key in your add
hash that is missing in your stock
hash : "NEW9788392289753".
When executing stock["NEW9788392289753"]
, nil
is returned, as the key is not mapped.
Upvotes: 3