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.rb733 chars40 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.rb132 chars7 lines
This should output:
main.rb172 chars10 lines
gistlibby LogSnag