访问哈希集合中对象的属性/方法

时间:2013-04-19 00:32:30

标签: ruby

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

这总是给我一个no方法错误。我试过让@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

感谢您对此事的任何帮助。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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