Reputation: 93
For whatever reason, I cannot access the position property inside the each loop.
This always give me a no method error. I've tried making the @position variable accessable a million different ways, and nothing seems to work.
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
error:
NoMethodError: undefined method `position' for nil:NilClass
Thanks for any help in this matter.
Upvotes: 0
Views: 108
Reputation: 425
I am not sure what you are trying to do. However I think your code should like this for it to work.
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
Upvotes: 0
Reputation: 61510
You have a typo in your call to the Recipe
constructor:
sandwich_recipe = Recipe.new("Sandwich",[
{ position: :on, ingredient: bread },
{ position: :on, ingredidnt: cheese }
]) ^
You mispelled ingredient
.
That being said, you never set the @position
instance variable to anything but nil
, so it will never have a value.
I think what you really want to do is pass the position to the Ingredient
constructor, then pass the array of ingredients to the Recipe
constructor.
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
Upvotes: 1