未定义的局部变量或方法“食物" [英] Undefined Local Variable or Method 'food'

查看:112
本文介绍了未定义的局部变量或方法“食物"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中工作时,出现错误提示

Working in Ruby, I'm getting an error saying

'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的代码

This is FoodDB.rb's code

class FoodDB
  def initialize
    food = []
  end

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

我不确定是什么问题,因为看来我肯定是在FoodDB类中调用了正确的方法.感谢所有帮助,谢谢!

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!

推荐答案

您需要将FoodDB类中的food更改为实例变量:

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

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

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.

这篇关于未定义的局部变量或方法“食物"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆