Ruby - 如何计算购物清单中项目的小计

Ruby - How to calculate subtotal of items in a grocery list

我想创建一个程序,用户基本上 "creates" 一个购物清单,用户在其中输入商品和价格,直到他们想退出。如果用户输入“q”或“Q”,则程序应停止提示用户,而是应计算小计,加上名义上的 6% 销售税,并显示合计结果。

我记下了用户输入商品和价格的第一部分,但我不知道如何让它告诉我小计并给他们收据。我已经试了7个小时了!!当我 运行 它时,它应该说:

Enter an item and its price, or ’Q/q’ to quit: eggs 2.13
Enter an item and its price, or ’Q/q’ to quit: milk 1.26
Enter an item and its price, or ’Q/q’ to quit: batteries 3.14
Enter an item and its price, or ’Q/q’ to quit: q
Receipt:
--------
eggs => .13
milk => .26
batteries => .14
---------
subtotal: .53
tax: [=11=].39
total: .92

这是我编写的代码:(谁能帮帮我???)

def create_list
puts 'Please enter item and its price or type "quit" to exit'
items = gets.chomp.split(' ')
grocery_list  = {}
index = 0 
until index == items.length
grocery_list[items[index]] = 1 
index += 1
end
grocery_list
end

def add_item (list)
items  = ''
until items == 'quit'
puts "Enter a new item & amount, or type 'quit'."
items = gets.chomp
if items != 'quit'
  new_item = items.split(' ')
  if new_item.length > 2
    #store int, delete, combine array, set to list w/ stored int
    qty = new_item[-1]
    new_item.delete_at(-1)
    new_item.join(' ')
    p new_item
  end
  list[new_item[0]]  = new_item[-1]
else
  break
end
end
list
end

 add_item(create_list)

 puts "Receipt: "
 puts "------------" 

不确定您是否需要哈希,因为它们用于存储键值对。 此外,您应该在定义变量的地方组织代码,然后是方法,最后是 运行 代码。保持方法简单。

#define instance variabes so they can be called inside methods
@grocery_list = [] # use array for simple grouping. hash not needed here
@quit = false # use boolean values to trigger when to stop things.
@done_shopping = false
@line = "------------" # defined to not repeat ourselves (DRY)

#define methods using single responsibility principle.
def add_item
  puts 'Please enter item and its price or type "quit" to exit'
  item = gets.chomp
  if  item == 'quit'
    @done_shopping = true
  else
    @grocery_list << item.split(' ')
  end
end

# to always use 2 decimal places
def format_number(float)
  '%.2f' % float.round(2)
end

#just loop until we're done shopping.
until @done_shopping
  add_item
end

puts "\n"
#print receipt header
puts "Receipt: "
puts @line

#now loop over the list to output the items in arrray.
@grocery_list.each do |item|
  puts "#{item[0]} => $#{item[1]}"
end

puts @line
# do the math
@subtotal = @grocery_list.map{|i| i[1].to_f}.inject(&:+) #.to_f converts to float
@tax = @subtotal * 0.825
@total = @subtotal + @tax

#print the totals
puts "subtotal: $#{format_number @subtotal}"
puts "tax: $#{format_number @tax}"
puts "total: $#{format_number @total}"
#close receipt
puts @line