Undefined Local Variable or Method 'food'

陌路散爱 提交于 2019-12-11 21:14:53

问题


Working in Ruby, I'm getting an error saying

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

This is the code I'm trying to run

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

This is FoodDB.rb's code

class FoodDB
  def initialize
    food = []
  end

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

I'm not sure what's the problem since it seems like I'm definitely calling the correct method from the FoodDB class. All help is appreciated, thank you!


回答1:


You need to change food in the FoodDB class to an instance variable:

class FoodDB
  def initialize
    @food = []
  end

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

An instance variable will be available throughout all methods of an instance, while the food variable you used was local to its lexical scope, i.e. only available within the initialize method.



来源:https://stackoverflow.com/questions/19488676/undefined-local-variable-or-method-food

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!