Paul Thompson Paul Thompson - 2 months ago 8
Ruby Question

Ruby: Food Menu that calculates and displays balance of your choice

Below is a method that displays a menu using a hash. I can't figure out how to use the input to then calculate and display the balance of the users choice/s. I'm also struggling with the concept of class initialization and how that could help here. Any help very welcome!

def product_menu

product_menu_hash = {
"Coffee" => 4.00,
"Soft Drink" => 4.00,
"Sandwich (Meat)" => 9.50,
"Sandwich (Veg)" => 8.00,
"Coffee Maker" => 50.00,
"Bag of Coffee (250g)" => 13.25,
}

puts "COFFEE SHOP"

product_menu_hash.each_with_index do |(item, price), index|
puts "#{index + 1} #{item} = $#{price}"
input = gets.chomp
end
end

Answer

The user is the shop assistant and I imagined them just entering the menu choice e.g. 1 for Coffee or 2 for soft drink etc then the price being calculated from there. Is there a way to do this?

Based on your last comment, a second answer would be

tot = 0
 product_menu_hash = {
"Coffee" => 4.00,
"Soft Drink" => 4.00,
"Sandwich (Meat)" => 9.50,
"Sandwich (Veg)" => 8.00,
"Coffee Maker" => 50.00,
"Bag of Coffee (250g)" => 13.25,
  }
 product_choice = {}

product_menu_hash.each_with_index do |(item,  price), index|
     product_choice[index+1]=item
    puts "#{index + 1} #{item} = $#{price}"
end
puts 'x to exit, p to print total   ' 
choice = gets.chomp
while choice != 'x' do
    if choice == 'p' then
        puts 'total: ', tot
    else
        puts product_choice[choice.to_i],product_menu_hash[product_choice[choice.to_i]]
        tot += product_menu_hash[product_choice[choice.to_i]]
    end
    choice = gets.chomp
end
Comments