Making a withdrawal oddity


#1




I have an interesting case here. I've completed the code. When I create a variable to initialize my Account class and call my display method as shown:

 checking_account= Account.new("Ryan's Account", 5000000)
 checking_account.display_balance(12345)

It goes right to the private 'pin_error' message I made within my private class..

Access denied: incorrect PIN.
nil

Here's where it gets strange. If i type the following:

 checking_account= Account.new("Ryan's Account", 5000000)
 checking_account.withdraw(12345, 5)
 checking_account.display_balance(12345)

it works.

 Withdraw $5. New balance: $4999995.
 Balance: $4999995
 nil



class Account
attr_reader :balance, :name
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 pin_number == pin 
        @balance-=amount
        puts "Withdraw $#{amount}. New balance: $#{@balance}."
    else
        puts pin_error
    end
  end


 private
 def pin
 @pin=12345
 end

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


checking_account= Account.new("Ryan's Account", 5000000)
checking_account.display_balance(12345)

It almost seems like it needs to have the withdraw method initialized first before being able to have the display method working.

Thanks for taking the time to read this!
Regards,
Ryan


Replace this line with your code.


#2

Found out the problem...... I used @pin instead of just the pin variable... lesson learned!
private method vs. private class variable....


#3

And the reason for "working" after making a withdrawal is that your withdrawal method called your pin method which creates @pin


#4

That makes sense, thanks ion


#5

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