Ruby 访问散列集合中对象的属性/方法

Ruby 访问散列集合中对象的属性/方法,ruby,Ruby,无论出于何种原因,我都无法访问each循环中的position属性 这总是给我一个无方法错误。我尝试了无数种不同的方式来访问@position变量,但似乎没有任何效果 class Recipe attr_accessor :directions def initialize(name,directions) @directions = directions end def directions @directions en

无论出于何种原因,我都无法访问each循环中的position属性

这总是给我一个无方法错误。我尝试了无数种不同的方式来访问@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

感谢您在这件事上提供的帮助。

您对
配方的调用中有一个输入错误
构造函数:

sandwich_recipe = Recipe.new("Sandwich",[
    { position: :on, ingredient: bread },
    { position: :on, ingredidnt: cheese }
])                          ^
你错卖了
配料

也就是说,您从未将
@position
实例变量设置为除
nil
之外的任何值,因此它永远不会有值

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

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

我不知道你想做什么。然而,我认为您的代码应该喜欢这样才能工作

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

一个拼写错误,使她失败了。我现在觉得自己很愚蠢。当我花一个多小时在某件事情上的时候,我真的必须开始做那些检查。。。无论如何,非常感谢!