Colin Marshall Colin Marshall - 9 months ago 55
Ruby Question

Program which will add items to a "grocerylist" array?

Here's the problem I'm working with:

The add_item method should take two arguments. The first argument is the item you want to add to the list and the second argument is the array (i.e. list) that the item will be added to. Don't add an item to the list if it already exists in the list.

Here is the code I have so far, and it keeps giving me an 'undefined local variable' error.

list = Array.new
list = [milk, eggs, oj, bacon]

def add_item(item, list)
if list.include?(item)
puts "item is already on list"
else list.push(item)

end
end

add_item(milk, list)

Answer Source

milk, eggs, oj, and bacon are all variables here but you don't show a definition. You could make them strings, e.g.

list = ["milk", "eggs", "oj", "bacon"]
# or a shorthand
list = %w{milk eggs oj bacon}
add_item("milk", list)

or symbols

list = [:milk, :eggs, :oj, :bacon]
# or a shorthand
list = %i{milk eggs oj bacon}
add_item(:milk, list)

In this case it doesn't matter which one you choose, but if the ingredient names can have special characters or spaces, it'd be easier to use strings.

Also rather than:

else list.push(item)

end

you should put the list.push(item) on the empty line.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download