下面是一个使用哈希显示菜单的方法。我无法弄清楚如何使用输入然后计算和显示用户选择的平衡。我也在努力学习类初始化的概念以及它在这方面有何帮助。任何帮助都非常欢迎!
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
答案 0 :(得分:1)
如果用户输入项目数量为整数
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,
}
puts "COFFEE SHOP"
product_menu_hash.each_with_index do |(item, price), index|
puts "#{index + 1} #{item} = $#{price}"
input = gets.chomp
totpar = input.to_i * price
puts totpar
tot += totpar
end
puts 'total: ', tot
答案 1 :(得分:0)
用户是店员,我想象他们只是进入了 菜单选择例如1咖啡或2软饮料等价格 从那里计算。有没有办法做到这一点?
根据您的上一条评论,第二个答案是
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