Home > Enterprise >  Ruby OOP - Instance Method
Ruby OOP - Instance Method

Time:10-27

Ruby OOP beginner here. Trying to build a simple Vending machine code.

class VendingMachine
  # TODO: add relevant getter/setter to this class to make the scenarios work properly.
  attr_reader :snack_price_cents, :user_balance_cents
  attr_accessor :snack_count

  def initialize(snack_price_cents, snack_count)
    @user_balance_cents = 0
    @snack_count = snack_count
    @snack_price_cents = snack_price_cents
  end

  def insert_coin(input_cents)
    @user_balance_cents = user_balance_cents   input_cents if input_cents
  end

  def buy_snack
    if snack_count.zero? || user_balance_cents.zero?
      @snack_count = snack_count
    else
      @snack_count = snack_count - 1
      @user_balance_cents = user_balance_cents - snack_price_cents
    end
  end
end

I am trying to understand what happens to snack_count, user_balance_cents and snack_price_cents when the user pushes a button to buy a snack?

It seems like all is working okay except for the user_balance_cents but I am getting:

should not let you buy a snack if you didn't insert enough money (error path) (FAILED - 1)"

error. Any help?

CodePudding user response:

I would guess that your error here is that you are checking that user_balance_cents is not zero, but you are not checking that it as least snack_price_cents.

i.e. if I put 10c in and try to buy a 50c snack, it will give me it.

  • Related