0

在 Ruby 中工作,我收到一条错误消息

'add': undefined local variable or method 'food' for #<FoodDB:...

这是我要运行的代码

require_relative 'FoodDB.rb'

class Manager
  def initialize
     food = FoodDB.new
     self.create_foodDB(food)
  end

  def create_foodDB(food)
    counter = 1
    word = []
    file = File.new("FoodDB.txt","r")   
    while (line = file.gets)
      food.addFood(line)
      counter = counter + 1
    end
    file.close
  end
end

manager = Manager.new

input_stream = $stdin
input_stream.each_line do |line|  
  line = line.chomp
  if line == "quit"
    input_stream.close
  end
end

这是 FoodDB.rb 的代码

class FoodDB
  def initialize
    food = []
  end

  def addFood(str)
    food.push(str)
  end
end

我不确定是什么问题,因为我似乎肯定从 FoodDB 类中调用了正确的方法。感谢所有帮助,谢谢!

4

1 回答 1

0

您需要将类更改foodFoodDB实例变量:

class FoodDB
  def initialize
    @food = []
  end

  def addFood(str)
    @food.push(str)
  end
end

实例变量将在实例的所有方法中可用,而您使用的 food 变量在其词法范围内是本地的,即仅在initialize方法内可用。

于 2013-10-21T07:45:21.033 回答