我想弄清楚为什么我的代码无效。如您所见,代码非常简洁。
有人可以帮我理解为什么我收到此错误消息:
“NoMethodError:undefined method`<<'为零:NilClass“
当我将此命令输入终端(加载脚本后):
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:in
add_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)
答案 0 :(得分:0)
将以下代码放在名为my_prog.rb的文件中:
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
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
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)
打开终端窗口并cd到与my_prog.rb相同的目录。然后运行你的程序:
ruby my_prog.rb
没有错误。