【发布时间】:2014-07-13 09:33:27
【问题描述】:
我想弄清楚为什么下面的代码不起作用。如您所见,代码非常简洁。
有人可以帮我理解为什么我会收到此错误消息:
"NoMethodError: 未定义的方法 `
当我将此命令输入终端时(加载脚本后):
mex_cuisine.add_recipe("charro beans")
脚本:
class Cookbook
attr_accessor :title, :recipes, :recipe
def initialize(title)
@title = title
@recipes = []
end
def add_recipe(recipe)
@recipe = recipe
@recipes << @recipe
end
end
class Recipe
attr_accessor :name, :ingredients, :steps
def initialize(name, ingredients, steps)
@name = name
@ingredients = ingredients
@steps = steps
end
end
非常感谢您的帮助。 谢谢。
**编辑:
替换此代码:
def add_recipe(recipe)
@recipes.push(recipe)
puts "Added a recipe to the collection: #{recipe.title}"
end
导致同样的错误...这是长版本:
NoMethodError: 未定义的方法
push' for nil:NilClass from cookbook.rb:10:inadd_recipe' 来自 (irb):173 来自 /Users/patrickmeaney/.rvm/rubies/ruby-2.1.1/bin/irb:11:in `'
**编辑:
这是给定的测试代码:
mex_cuisine = Cookbook.new("Mexican Cooking")
burrito = Recipe.new("Bean Burrito", ["tortilla", "bean"], ["heat beans", "place beans in tortilla", "roll up"])
mex_cuisine.recipes # []
mex_cuisine.add_recipe(burrito)
【问题讨论】:
-
mex_cuisine 到底是什么?能否请您也发布错误的堆栈跟踪?
-
您发布的代码没有产生错误。
-
很奇怪。它确实有效。我想知道发生了什么……每次编辑时我都在重新加载脚本。也许我没有正确初始化新类,所以它们为零?对不起这个菜鸟。
标签: ruby