2017-10-06 4 views
3

ユーザーが基本的に食料品リストを作成して、ユーザーがアイテムと価格を入力して終了したいときにプログラムを作成したいと考えています。ユーザーが 'q'または 'Q'を入力すると、プログラムはユーザーにプロンプ​​トを表示せず、代わりに小計を計算し、公称6%の消費税を加算し、合計結果を表示する必要があります。Ruby - 食料品リストのアイテムの小計を計算する方法

私はユーザーが項目と価格を入力するところで最初の部分を取得しましたが、小計を教えて領収書を与える方法はわかりません。私は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 => $2.13 
milk => $1.26 
batteries => $3.14 
--------- 
subtotal: $6.53 
tax: $0.39 
total: $6.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 "------------" 

答えて

1

ないあなたは彼らのように、このためのハッシュを必要としてください、私はそれを実行すると、言うことになっていますキー値のペアを格納するために使用されます。 また、変数を定義し、次にメソッドを定義し、コードを最後に実行するコードを整理する必要があります。メソッドを単純なままにしておきます。

#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 
関連する問題