Banking on ruby - Pin error


#1

Hello there,

Could someone please explain me why i always get "access denied: incorrect PIN" when I call checking_account.display_balance(1234) ?

The pin is correct so it should work. At first i thought that maybe pin_number was a string and @pin an integer so I tried pin_number.to_i == @pin but it doesnt work either.

class Account
attr_reader :name, :balance
def initialize(name, balance=100)
@name = name
@balance = balance
end

private
def pin
    @pin = 1234
end

def pin_error
    return "Access denied: incorrect PIN."
end

public
def display_balance(pin_number)
    if pin_number == @pin
        puts "Balance: $#{@balance}"
    else
        pin_error
    end
end

def withdraw(pin_number, amount)
    if pin_number == @pin
        @balance -= amount
        puts "Withdrew #{amount}. New balance: $#{@balance}"
    else
        pin_error
    end
end

end

checking_account = Account.new("Richy","2000")
checking_account.display_balance(1234)


#2

You're comparing the pin number to @pin which is undefined (you'll get nil when accessing it)

Use your method instead, and have your method return the pin instead of creating an instance variable.


#3

Thanks for your reply,

I don't understand why @pin is undefined since there is a methode to define it and to give it a value of 1234.

Also, this is the way the program is coded in the exemple given on the first step of the lesson and it does work when you run it, what could be the difference between mine and the exemple given by codecademy ?


#4

Exercise 4:

02. The body of your method should check whether the pin_number is equal to pin (the result of calling the private pin method)

Now why does that method also create an istance variable? Don't know. But you're supposed to call it. If you don't invoke the method then it will never return or set anything.


#5

Thank you for your answer, that helped a lot!
I was wondering for half an hour why my display_balance would work when I setted my pin on "nil" and not when setted on "1234"...
Now I finnaly understand this private and public stuff :stuck_out_tongue: