vending machine in ruby

To implement a vending machine in Ruby, we can start by defining a VendingMachine class with instance variables for the items in stock and the current balance of the user. We can also define constants for the prices of each item.

main.rb
class VendingMachine
  ITEMS = {
    "Coke" => 1.5,
    "Chips" => 2.0,
    "Candy" => 1.0
  }

  def initialize
    @stock = ITEMS.dup
    @balance = 0
  end

  def insert(amount)
    @balance += amount
    puts "Current balance: #{@balance} dollars"
  end

  def select(item)
    if @stock.key?(item)
      price = ITEMS[item]
      if @balance >= price
        @balance -= price
        @stock[item] -= 1
        puts "Dispensing #{item}..."
        puts "Current balance: #{@balance} dollars"
      else
        puts "Please insert #{price - @balance} more dollars"
      end
    else
      puts "Invalid item: #{item}"
    end
  end

  def stock
    @stock.each do |item, count|
      puts "#{item}: #{count}"
    end
  end
end
733 chars
40 lines

Here, we use a hash to keep track of the items in stock and their prices. The insert method allows the user to add money to their balance, and the select method allows the user to purchase an item. If the user has enough balance and the item is in stock, the item is dispensed and the balance is updated. Otherwise, an error message is displayed. The stock method displays the current stock of the vending machine.

We can test the vending machine by creating an instance and calling its methods:

main.rb
machine = VendingMachine.new
machine.insert(2)
machine.select("Chips")
machine.select("Coke")
machine.select("Candy")
machine.stock
132 chars
7 lines

This should output:

main.rb
Current balance: 2 dollars
Dispensing Chips...
Current balance: 0.0 dollars
Dispensing Coke...
Please insert 0.5 more dollars
Invalid item: Candy
Coke: 0
Chips: 1
Candy: 1
172 chars
10 lines

gistlibby LogSnag