获取(NoMethodError)就好像没有创建对象一样

时间:2013-10-30 23:19:34

标签: ruby

我在运行以下内容时遇到了困难。我收到以下错误 “':nil的未定义方法`name':NilClass(NoMethodError)” 在

puts shopper[i].name

线

好像有时在到达该行时尚未创建对象

(0 .. 9).each do |i|
  shopper[i] = Shopper.new("Shopper Number-#{i}")
  (0 .. 19).each do |j|
    r = rand(0 .. (k-1))
    if shopper[i].unsuccessful_shopping_trip == true
      puts "#{shopper[i].name} has failed to buy 3 times and has decided to go home"
      i += 1
      break
    else
      if shopper[i].add_product(shop.remove_product_bought_by_shopper(r)) == false
        puts "#{shopper[i].name} has tried to buy #{(shop.products[r]).name} but it is sold out"
        j -= 1
      else
        puts "#{shopper[i].name} has bought #{(shop.products[r]).name}"
      end
    end
  end

  puts shopper[i].name
  puts shopper[i].shopping_list
  total_shopper_net += shopper[i].total_net_value
  total_shopper_gross += shopper[i].how_much_spent
  total_shopper_product_count += shopper[i].total_product_count

end

任何人都能解释一下吗?

1 个答案:

答案 0 :(得分:1)

您在i迭代器中手动递增each。对shopper[i]的任何后续引用尚不存在,因为购物者仅在循环的顶部创建。