创建代码以根据用户输入进行更改

时间:2017-05-19 17:41:53

标签: ruby

我被任务困扰了。我必须编写代码来创建一个虚拟糖果机,它将迎合用户,列出所有糖果选择,确认金额/糖果选择用户输入,并根据需要发出变化和糖果。我发现自己无法创建代码来让机器确认糖果选择并给出更改。基本上我正在尝试创建能够响应用户需求的代码。请帮忙。这是我到目前为止的代码:

puts "hello"
puts "welcome to candy machine"
puts candy = Array["A - oreo", "B - twix", "C - chips", "D - gum"]
Candy = Hash["oreo" => 1 "twix" => 2, "chips" => 3, "gum" => 4]
puts "would you like to order? Select 1, 2, 3, 4
user_input = gets.chomp
price = Array[1.20, 1.25, 1.00, 0.50]
puts "You selected:"
puts "#{Candy[user_input]}"
puts "please pay", "#{price[user_input]}"

1 个答案:

答案 0 :(得分:0)

我认为,正如评论所提到的,你有很多错误,但我认为他们是在SO上打字。

问题是你正在使用哈希,使用字符串键 - 每个糖果的单词,但要求索引。反转您的哈希,它应该工作。

即。改变这个:

candy = Hash["oreo" => 1 "twix" => 2, "chips" => 3, "gum" => 4]

到:

candy = [1 => 'oreo', 2 => 'twix', 3 => 'chips', 4 => 'gum']

与价格数组相同