ruby - 如何将先前循环迭代的计算值相加?
问题描述
我想知道如果可以保存和总结以前循环迭代中的以前的值。
所以我有这段代码来遍历一系列杂货,然后总结购买了多少特定商品。这是我的代码。
groceries = %w[apples quinoa peppers milk butter]
item = 0
groceries.each do |_i|
puts 'what groceries are you getting?'
grocery_choice = gets.chomp
apples = 2.30
quinoa = 2.75
milk = 1.80
butter = 3.25
peppers = 3.00
puts "how many #{grocery_choice} are you getting?"
number_of_particular_grocery = gets.to_i
if grocery_choice == 'apples'
item = apples
elsif grocery_choice == 'quinoa'
item = quinoa
elsif grocery_choice == 'milk'
item = milk
elsif grocery_choice == 'butter'
item = butter
elsif grocery_choice == 'peppers'
item = peppers
elsif grocery_choice == 'none'
break
end
total = item * number_of_particular_grocery
puts "when you buy #{number_of_particular_grocery} #{grocery_choice} it costs #{total}"
total += total
end
puts " your total grocery bill is #{total.sum { |total, _t| total }}"
最后一行坏了,但我想做的基本上是
total_cost = total_milk + total_butter + total_apples + total_peppers
但没有在程序中明确写出来。有没有办法total
从循环的上一个迭代中保存并在它之后从循环迭代中添加到下一个total
?
解决方案
我会重新开始您的问题并考虑以下内容:
GROCERY = {
apples: 2.30,
quinoa: 2.75,
peppers: 3.00,
milk: 1.80,
butter: 3.25
}
def add_grocery_item(bag, item, qty)
bag.push([item, qty, GROCERY[item]])
end
if __FILE__ == $0
grocery_bag = []
add_grocery_item(grocery_bag, :apples, 10)
add_grocery_item(grocery_bag, :quinoa, 1)
add_grocery_item(grocery_bag, :milk, 2)
add_grocery_item(grocery_bag, :butter, 3)
add_grocery_item(grocery_bag, :apples, 7)
add_grocery_item(grocery_bag, :quinoa, 6)
add_grocery_item(grocery_bag, :milk, 6)
add_grocery_item(grocery_bag, :butter, 9)
p grocery_bag.reduce(Hash.new(0)){|acc, e| acc[e[0]] += e[1] * e[2]; acc}
end
这只是一个需要考虑的起点。
推荐阅读
- javascript - 如何使用 JavaScript 将移动功能添加到多个项目
- javascript - 在 Angular 应用程序中将 FirebaseAuth.onAuthStateChanged 调用放在哪里?
- python - 如何切换到 Windows 安全窗口并插入凭据
- sql - 如何使用 Max 函数过滤列表并插入
- asp.net-core - Swashbuckle.AspNetCore 5.0.0-rc4 UploadFileFilter 不起作用
- python-3.x - 通过 pygithub 使用 SSH 密钥
- java - 添加 Firebase 存储作为依赖项会使应用程序崩溃
- sql-server - SQL - 汇总聚合子查询
- r - 根据R中的数据帧名称合并存储在不同长度列表中的数据帧
- python - 如何将 django 查询集中的实例总和附加到该查询集中?