byebugを使って順にデバッグを実行していたら、__NameError Exception: undefined local variable or method `drink' for VendingMachine:Class__と表示されたが原因となる部分が見当たらず自己解決に至りませんでした。
エラーの原因を説明していただきたいです。
下記がvending_machine.rbのコードになります。
Ruby
1require './drink' 2 3class VendingMachine 4 require 'byebug'; byebug 5 USEABLE_MONEY = [10, 50, 100, 500, 1000] 6 attr_reader :total, :sale_amount 7 8 #初期化 9 def initialize 10 @total = 0 11 @sale_amount = 0 12 @drink_table = {} 13 #ドリンククラスを作成したら5本格納の文を書く 14 5.times { store Drink.coke } 15 end 16 17 #投入金額 18 def insert(money) 19 USEABLE_MONEY.include?(money) ? nil.tap { @total += money } : money 20 end 21 22 #お釣り 23 def change 24 total.tap { @total = 0} 25 end 26 27 def store(drink) 28 nil.tap do 29 @drink_table[drink.name] = { price: drink.price, drinks: [] } unless @drink_table.has_key? drink.name 30 @drink_table[drink.name][:drinks] << drink 31 end 32 end 33 34 def purchase(drink_name) 35 if purchaseable? drink_name 36 drink = @drink_table[drink_name][:drinks].pop 37 @sale_amount += drink.price 38 @total -= drink.price 39 [drink,change] 40 end 41 end 42 43 def purchaseable?(drink_name) 44 purchaseable_drink_names.include? drink_name 45 end 46 47 def purchaseable_drink_names 48 @drink_table.select{|_, info| info[:price] <= total && info[:drinks].any? }.keys 49 end 50 51 def stock_info 52 Hash[@drink_table.map {|name, info| [name, { price: info[:price], stock: info[:drinks].size }] }] 53 end 54 55end
drink.rbのコード↓
Ruby
1class Drink 2 attr_reader :name, :price 3 4 def self.coke 5 self.new 120, :coke 6 end 7 8 def self.redbull 9 self.new 200, :redbull 10 end 11 12 def self.water 13 self.new 100, :water 14 end 15 16 def initialize price, name 17 #インスタンス変数 18 @name = name 19 @price = price 20 end 21 22 def ==(another) 23 self.name == another.name 24 end 25 26 def eql?(another) 27 self == another 28 end 29 30 def hash 31 name.hash 32 end 33 34 def to_s 35 "<Drink: name=#{name}, price=#{price}>" 36 end 37end
回答1件
あなたの回答
tips
プレビュー