Need help with pin within withdraw


#1



class Account
    attr_reader :name, :balance
    def initialize(name, balance=100)
        @name = name
        @balance = balance
    end
    
    def display_balance(pin_number)
         puts pin_number == pin ? "Balance: #{@balance}." : pin_error
     end
    
    def withdraw(pin_number, amount)
        if amount > @balance 
            return overdraft
        elsif
            pin_number == pin
            @balance-=amount
        puts  "Withdrew #{amount}. New balance: #{@balance}." 
        else 
            return pin_error
        end
    end
    
    def deposit(pin_number, amount)
    @balance+=amount
    puts  pin_number == pin ? "Deposited #{amount}. New balance: $#{@balance}." : pin_error
    end
    

    private
    
    def pin
        @pin = 1234
    end
    
    def pin_error
        puts "Access denied: incorrect PIN."
    end
    
    def overdraft 
        puts "Denied, #{amount} exceeds the current balance: #{@balance}."
    end

end

class CheckingAccount < Account
end
class SavingsAccount < Account
end

checking_account = Account.new("Joe", 100000)
checking_account.withdraw(1234, 500)
checking_account.display_balance(1234)


#2

the code is returning:
Withdrew 50. New balance: 99950.
Balance: 99950.
nil

which is working fine, however, the overdraft code within withdraw only requires that the amount exceeds the balance before returning overdraft, without checking that the pin_number == pin. how would i go about writing the code so that it must check that the pin_number == pin before checking that whether the amount > balance.


#3

Put the pin check before everything else

unless pin_number == pin
    # access denied
end

Also, your indentation could use some work


#4

ive done it like
def withdraw(pin_number, amount)
if pin_number == pin
amount > @balance
return overdraft

and when i do so, the code breaks and returns:

Denied, exceeds the current balance: 100000.
Balance: 100000.
nil


#5

Forget about code for a while and just ask yourself what order events should take place.


#6

idealy, it should check to make sure the pin is correct before anything else, but im not sure how to write the code to do so, so i have just tried:

def withdraw(pin_number, amount)
unless pin_number == pin
pin_error
end
if amount > @balance
return overdraft

and the code seems to be running correctly, i see my error and i appreciate the help.


#7

Tbh I'm not a fan of "unless" but it seemed like the ruby way of writing that. Perhaps I'd be ok with it after getting more used to it.

Negation is generally very difficult to read and understand, double negation is an immediate call for re-writing something.


#8

It does seem to be working correctly, im pretty new to programming in general, my first language, but I do appreciate the help, and I will work on my indentation! thanks


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.