我这样做了吗?如果没有,请有人解释它应该如何工作?

时间:2018-03-23 23:57:15

标签: ruby

您好我想知道我的代码有什么问题

 pizza = "2.99"

puts "hello what would you like to buy?"
food_type = gets.chomp.downcase

puts "How many?"
food_amount = gets.chomp!

puts #{food_amount.to_i * food_type.to_f}

1 个答案:

答案 0 :(得分:2)

要做这样的事情,你应该用哈希值存储不同类型的食物,并使用{ "food type" => cost of food }(例如,{ 'pizza' => 9.99, 'soda' => 2.99, 'breadsticks' => 1.50 })注意价格已经是浮点数,因此以后不需要转换

然后当你循环时,你可以将他们购买的东西保存在另一个散列{ 'food type' => quantity }中,数量为整数。然后,当他们完成选择项目时,你会遍历“购物车”并将所有内容相乘:

menu = { 'pizza' => 9.99, 'soda' => 2.99, 'breadsticks' => 1.50 }
cart = Hash.new(0)

begin
  puts "hello what would you like to buy?"
  food_type = gets.chomp.downcase

  puts "How many?"
  quantity = gets.to_i

  cart[food_type] += quantity

  puts "Want Anything Else?"
  buy_more = (gets.chomp == "yes")
end while buy_more

puts "you're buying:"
cart.each do |food_type, quantity|
  puts "#{quantity} of #{food_type} for #{quantity * menu.fetch(food_type, 0)}"
end

示例运行:

hello what would you like to buy?
soda
How many?
2
Want Anything Else?
yes
hello what would you like to buy?
pizza
How many?
5
Want Anything Else?
yes
hello what would you like to buy?
breadsticks
How many?
1
Want Anything Else?
yes
hello what would you like to buy?
something else
How many?
10
Want Anything Else?
no
you're buying:
2 of soda for 5.98
5 of pizza for 49.95
1 of breadsticks for 1.5
10 of something else for 0

了解有关Hash in the docs的更多信息,该信息应该包含足够的信息,让您了解我尚未添加的repl部分,并决定如何处理无效条目(例如我输入时)其他'为食物类型)。此示例仅将其视为无效的有效项目。