I am trying to add an element into an instance of array by using push(<<) to insert variables new_name and new_origin into ingredients array but I am receiving this error: undefined method `name’ for an instance of Array (NoMethodError)
There are two class instances – Menu and Ingredient
class Menu
attr_accessor : dessert, :ingredients
def initialize (dessert, ingredients)
@dessert = dessert
@ingredients = ingredients
end
end
class Ingredient
attr_accessor :name, :origin
def initialize (name, origin)
@name = name
@origin = origin
end
end
After a text file that contains Menu and ingredient information, I want to add a new ingredient information to the existing information.
Created arrays – menu and ingredient
menu = Menu.new(dessert, ingredients)
ingredient = Ingredient.new(name, origin)
Where error occurs
This below code: update the existing menu information
read_string is a function that display the prompt and return the read string.
#menus contains the read menu file information
def menu_update(menus)
menu_id = read_integer_in_range("Enter the Menu to edit: ", 1, menus.length)
menu_id = menu_id - 1
ingredient_count = menus[menu_id].ingredients.length
new_name = read_string("Enter a name for new ingredient: ")
new_origin = read_string("Enter a origin for new ingredient: ")
menus[menu_id].ingredients.name << new_name
menus[menu_id].ingredients.origin << new_origin
puts("Update info"
puts("Name: #{menus[menu_id].ingredients[ingredient_count].name}")
puts("Name: #{menus[menu_id].ingredients[ingredient_count].origin}")
end
Expected output:
Update info
Name: peanut
Location: USA
Sulsoyy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.