0

无论出于何种原因,我都无法访问每个循环内的位置属性。

这总是给我一个无方法错误。我已经尝试让@position 变量以一百万种不同的方式访问,但似乎没有任何效果。

class Recipe
    attr_accessor :directions
    def initialize(name,directions)
        @directions = directions
    end

    def directions
        @directions
    end

    def make
        ingredients = []
        @directions.each do |dir|
            puts dir[:ingredient].position
            #puts ingredient.position
            #direction[:ingredient].position = direction[:position]
            #ingredients.push(direction[:ingredient])
        end
    end
end

class Ingredient

    attr_accessor :name, :position
    def initialize(name)
        @name = name
        @position = nil
        @state = nil
    end

end


bread = Ingredient.new("bread")
cheese = Ingredient.new("cheese")

sandwich_recipe = Recipe.new("Sandwich",[
    { position: :on, ingredient: bread },
    { position: :on, ingredidnt: cheese }
])

sandwich = sandwich_recipe.make
#sandwich.inspect

错误:

NoMethodError: undefined method `position' for nil:NilClass

感谢您在这件事上的任何帮助。

4

2 回答 2

1

您在调用Recipe构造函数时有错字:

sandwich_recipe = Recipe.new("Sandwich",[
    { position: :on, ingredient: bread },
    { position: :on, ingredidnt: cheese }
])                          ^

你拼错了ingredient

话虽如此,您永远不会将@position实例变量设置为除 之外的任何nil值,因此它永远不会有值。

我认为您真正想要做的是将位置传递给Ingredient构造函数,然后将成分数组传递给Recipe构造函数。

class Ingredient
    attr_accessor :name, :position

    def initialize(name, position)
        @name = name
        @position = position
    end
end

bread  = Ingredient.new("bread",  "on")
cheese = Ingredient.new("cheese", "on")

sandwich_recipe = Recipe.new("Sandwich", [bread, cheese])
sandwich = sandwich_recipe.make
于 2013-04-19T00:40:16.993 回答
0

我不确定您要做什么。但是我认为您的代码应该喜欢这样才能正常工作。

class Recipe
    attr_accessor :directions
    def initialize(name,directions)
        @directions = directions
    end

    def directions
        @directions
    end

    def make
        ingredients = []
        @directions.each do |element|
            puts element.name
            puts element.position
            #puts ingredient.position
            #direction[:ingredient].position = direction[:position]
            #ingredients.push(direction[:ingredient])
        end
    end
end

class Ingredient

    attr_accessor :name, :position
    def initialize(name, position)
        @name = name
        @position = position
        @state = nil
    end

end


bread = Ingredient.new("bread", "on")
cheese = Ingredient.new("cheese", "on")

sandwich_recipe = Recipe.new("Sandwich",[ bread, cheese ])
sandwich = sandwich_recipe.make
于 2013-04-19T00:40:25.997 回答