-
Notifications
You must be signed in to change notification settings - Fork 0
/
vending_machine.rb
73 lines (57 loc) · 1.63 KB
/
vending_machine.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
require "pry"
class VendingMachine
ACCEPTABLE_MONEY = [10, 50, 100, 500, 1_000].freeze
# stocks: 現在の在庫
# total_money_amount: 現在の投入金額合計
# sales_amount: 売上金額合計
attr_reader :total_money_amount, :sales_amount
attr_writer :stocks
def initialize(stocks: {})
@total_money_amount = 0
# stocsk は
# {
# {'コーラ' => {price: 120, count: 5}},
# {'オレンジジュース' => {price: 100, count: 2}},
# {'エナジードリンク' => {price: 200, count: 4}}
# }
# のようなハッシュでもってみる
@stocks = stocks.dup
@sales_amount = 0
end
def stocks
@stocks.dup
end
def insert_money(money)
return money unless ACCEPTABLE_MONEY.include?(money)
@total_money_amount += money
end
def refund
change = @total_money_amount
@total_money_amount = 0
change
end
def sell(drink_name)
if can_buy?(drink_name)
@stocks[drink_name][:count] -= 1
@sales_amount += @stocks[drink_name][:price]
@total_money_amount -= @stocks[drink_name][:price]
@total_money_amount
end
end
def add_stock(drink)
@stocks = @stocks.merge(drink)
end
def buyable_drinks
# XXX インデックスでアクセスするのがダサいしわかりづらく感じる
@stocks.each_with_object([]) do |drink, memo|
memo << drink[0] if drink[1][:price] <= @total_money_amount
end
end
private
def can_buy?(drink_name)
return false unless @stocks
price = @stocks[drink_name][:price]
count = @stocks[drink_name][:count]
(total_money_amount >= price) && (count >= 1)
end
end