首页 > 解决方案 > 如何将先前循环迭代的计算值相加?

问题描述

我想知道如果可以保存和总结以前循环迭代中的以前的值。

所以我有这段代码来遍历一系列杂货,然后总结购买了多少特定商品。这是我的代码。

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

标签: ruby

解决方案


我会重新开始您的问题并考虑以下内容:

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

这只是一个需要考虑的起点。


推荐阅读