【问题标题】:Ruby newb requesting assistance with basic classesRuby newb 请求基本类的帮助
【发布时间】: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


【解决方案1】:

将以下代码放入名为 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

不会有错误。

【讨论】:

  • 我认为问题只是在编辑 Cookbook 类后未能重新初始化类(在终端中——我一直通过终端输入所有测试代码)(只是我的怀疑)
  • 你所说的“终端”是指irb吗?如果是这样,我认为您会发现使用名称为 a.rb、b.rb、c.rb 的练习文件比在 irb 中尝试要容易得多。 irb 是一种痛苦。
  • 是的,我使用的是 IRB。我使用的教程只是建议使用一种“test_code.rb”文件,类似于你的建议。感谢您的有用建议。
猜你喜欢
  • 1970-01-01
  • 2011-10-14
  • 2012-06-22
  • 2020-06-06
  • 2012-01-15
  • 1970-01-01
  • 1970-01-01
  • 2011-07-19
  • 1970-01-01
相关资源
最近更新 更多