class Account
def initialize(starting_balance = 0)
@balance = starting_balance
end
def balance #instance getter method
@balance #instance variable visible only to this object
end
def balance=(new_amount)
@balance = new_amount
end
def deposit(amount)
@balance+=amount
end
@@bank_name= "MyBank.com" # class (static) variable
# A class method
def self.bank_name
@@bank_name
end
# or: def SavingsAccount.bank_name : @@bank_name : end
end
I want to understand the code snippets in bold. What do they do? what is the difference between a setter and initialize method.
If I had an object test=Account.new() and why is test(30) giving an error. Isn’t that suppose to call the setter method with parameter 30 and set the balance?
initializeis the method that is called on the newly created object when you doAccount.neworAccount.new(my_starting_balance). In the first caseinitializewould be called with the default value0forstarting_balanceand in the second withmy_starting_balance.The setter method
balance=is called when you domy_account.balance = some_valuewheremy_accountis an instance of the classAccount. So if you have the following code,initializewill be called on line 1 (with 0 as its argument) andbalance=on line 2 (with 23) as its argument:Of course in this case I could just as well write the following and not use the setter method at all:
However that doesn’t always work because some times you might want to change the value of
balanceafter the object has already been created.Because
test(30)means “call the methodtestwith the argument 30″ and there is no method calledtestin your code.Regarding the second bolded part of your code: As the comments indicate, it sets a class variable named
@@bank_nameand defines a class method that returns that variable’s value.