I'm just starting Ruby and have a beginner question. Why is it that when pin_number == @pin (in the display_balance and withdraw methods), I get an error, but when I edit to set pin_number == pin, both methods then work?
In the methods below, I have the private class pin setting @pin = 1234, so I thought that should have worked using @pin and not pin.
class Account
attr_reader :name, :balance
def initialize(name, balance=100)
@name = name
@balance = balance
end
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 #{amount}."
else
pin_error
end
end
private
def pin
@pin = 1234
end
def pin_error
return "Access denied: incorrect PIN."
end
end
checking_account = Account.new("Rick", 1_000_000)
checking_account.display_balance(1234)
Below the methods, I have the private class pin setting @pin = 1234, so I thought that should have worked using @pin and not pin.
No; pin calls that method, which both sets @pin = 1234 and returns its value.
Referencing @pin just references that variable and nothing more; it does not invoke the private pin method.
I believe this should answer your other questions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With