Banking on Ruby


#1

the lesson code as follows:
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 pin_number == pin
@balance -= amount
puts "Withdrew #{amount}. New balance: $#{@balance}."
else
puts pin_error
end
end

private

def pin
@pin = 1234
end

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

my_account = Account.new(“Eric”, 1_000_000)
my_account.withdraw(11, 500_000)
my_account.display_balance(1234)
my_account.withdraw(1234, 500_000)
my_account.display_balance(1234)

My question is why variable pin does not have @ sign when it is called in other method like withdraw. When I do my code with @ sign, the program does not work right.
Thank you for your advise.


#2

Because pin is a method that returns the @pin value. In general terms we would refer to this as a getter. Note also that the method is private so cannot be accessed outside of the class.


#3

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