我的程序不是 saving/displaying 我添加的所有账单

My program isn't saving/displaying all the bills I've added

我过去一直在学习网络开发,但没有时间,因为我是一名全日制商科学生。

我今天开始重新挖掘,决定休息一下,通过编写一个简单的程序来实践我今天学到的知识,该程序允许用户输入他们的账单并最终计算出多少可支配收入他们每月支付账单后。

我的问题是程序完美运行,循环在应该的时候是 continuing/exiting,但是程序没有像我希望的那样将用户输入存储在哈希中,或者没有显示所有输入的账单。这是我的程序:

# This program allows you to assign monthly payments
# to their respective bills and will automatically
# calculate how much disposable income you have
# after your bills are paid

# Prompts user to see if they have any bills to enter
puts "Do you have any bills you would like to enter, Yes or No?"
new_bill = gets.chomp.downcase
 until new_bill == 'no'

# Creates a hash to store a key/value pair 
# of the bill name and the respection payment amount

    bills = {}
    puts "Enter the bill name: "
    bill_name = gets.chomp
    puts "How much is this bill?"
    pay_amt = gets.chomp

    bills[bill_name] = pay_amt

    puts "Would you like to add another bill, Yes or No?"
    new_bill = gets.chomp.downcase
end

bills.each do |bill_name, pay_amt|
  puts "Your #{bill_name} bill is $#{pay_amt}."
end 

我的问题是: 我的散列设置是否正确以存储来自用户输入的 key/value 对? 如果不是,我该如何更正?

我只收到用户输入的最后一张账单。我一次尝试了好几张账单,但只收到最后一张。

正如我所说,我是一个菜鸟,但我非常渴望学习。我已经参考了关于散列的 ruby 文档以查看我的代码中是否存在错误,但能够找到解决方案(仍在寻找解决方法 ruby 文档)。

感谢任何帮助!另外,如果您对我可以提高代码效率的方法有任何建议,您能否指出我可以获得适当信息的方向?

谢谢。

编辑:

主要问题已得到解答。这是同一程序的后续问题 - 我收到一条错误消息 budget_calculator.rb:35:in -': Hash can't be coerced into Float (TypeError) from budget_calculator.rb:35:in'

来自以下代码(记住上面的程序)-

# Displays the users bills
bills_hash.each {|key,value| puts "Your #{key} bill is $#{value}."}

# Get users net income
puts "What is your net income?"
net_income = gets.chomp.to_f

#Calculates the disposable income of the user
disposable_income = net_income - bills_hash.each {|value| value}

puts disposable_income

我知道这行代码出现了错误: disposable_income = net_income - bills_hash.each {|值|值}

我只是不明白为什么这是不可接受的。我试图从净收入中减去散列 (pay_amt) 中的所有值以得出可支配收入。

这是让您满意的部分:

bills = {}

每次程序循环时,您都在重置散列。尝试在程序顶部声明 bills


关于您关于 bills_hash 的第二个问题,它不起作用,因为该程序试图从浮点数中减去散列。您的想法是正确的,但它的设置方式不会只是依次从 net_income 中减去每个键。

#each 的 return 值是您循环的原始哈希值。如果你打开 IRB 并输入

,你可以看到这个
[1,2,3].each {|n| puts n}

为列表的每个元素评估块,但最终的 return 值是原始列表:

irb(main):007:0> [1,2,3].each {|n| puts n}
1
2
3
=> [1, 2, 3]   # FINAL RETURN VALUE

因此根据操作顺序,您的 #each 块正在迭代,然后 return 原始 bills_hash 散列,然后尝试从 [=18] 中减去该散列=],看起来像这样(假设我的 net_income 是 1000):

1000 - {rent: 200, video_games: 800}

因此出现错误。

有几种方法可以解决这个问题。一种是将 bills_hash 中的所有值相加作为它自己的变量,然后从 net_income:

中减去它
total_expenditures = bills_hash.values.inject(&:+) # sum the values
disposable_income = net_income - total_expenditures

使用相同的 #inject 方法,这也可以在一个函数调用中完成:

disposable_income = bills_hash.values.inject(net_income, :-) 
# starting with net_income, subtract each value in turn

请参阅 Enumerable#inject 的文档。

这是一个非常强大和有用的了解方法。但是请务必回过头来了解 return 值的工作原理以及原始设置引发异常的原因。