无论出于何种原因,我都无法访问每个循环内的位置属性。
这总是给我一个无方法错误。我已经尝试让@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
感谢您在这件事上的任何帮助。