I am completely new to Ruby and thus I am not quit sure how to
troubleshoot this issue. I have looked at other forums and found nothing
that helps my particular situation.
I am trying to count the number of “Chicken Sandwich” products sold each
week for 8 weeks starting 1/4/2015 - 1/10/2015.
I have successfully run this code when I only attempt one week (so the
same script except lines 23,34,35,36) but as soon as I introduce a while
loop to go over the 8 weeks, or create a different function for each
week I get the same error. It seems that after I use the code in lines
29-33 once I can’t use it again in the same script, even if I change the
array name (item_arrey) and change the parsed JSON data object name
(items_js) across different functions.
For this script, the error occurs in line 29 in ‘fetch_lto_info’:
undefined method ‘[]’ for nil:NilClass from line 40 in
‘’
Any advice would be awesome remember though, I’m a noob. Thanks.
Thanks raubarede, but I’m still getting the same error on line 29…
======
29 items_js[“Data”][“SalesDetails”].each do |item_arrey|
30 if item_arrey[“Title”] == “Chicken Sandwich”
31 lto_week[week_num] += item_arrey[“ItemCount”]
32 end
33 end
for a couple of the weeks the array items_js[“Data”][“SalesDetails”] may
be empty (i.e. []). So that may be causing the error but I’m not quite
sure how to get around that.
Thanks raubarede, but I’m still getting the same error on line 29…
======
29 items_js[“Data”][“SalesDetails”].each do |item_arrey|
30 if item_arrey[“Title”] == “Chicken Sandwich”
31 lto_week[week_num] += item_arrey[“ItemCount”]
32 end
33 end
for a couple of the weeks the array items_js[“Data”][“SalesDetails”] may
be empty (i.e. []). So that may be causing the error but I’m not quite
sure how to get around that.
the <<undefined method ‘[]’ for nil:NilClass>> error mean
that you apply [] on a data which is nil.
if you apply [] on a empty array (or a hash whch has not the key)
, you get nil (without error):
{a: 1}[‘a’] >> 1
{b: 1}[‘a’] >> nil
nil[0] >> undefined method ‘[]’ for ni…
On this context, i think that ‘items_js’ has no field ‘Data’ ,
so items_js[“Data”] give nil , then nil[“SalesDetails”] give
your error.
try
if items_js[“Data”] && items_js[“Data”][“SalesDetails”]
items_js[“Data”][“SalesDetails”].each {…}
end
Perhaps, a more rubyst code can be
if items_js[‘Data’] && items_js[‘Data’][“SalesDetails”]