Hello.
Can anyone pinoint me where I made a mistake?
Error message is as follows:
accounts.rb(main):038:0> accounts.transferToSavings(100)
NoMethodError: undefined method `balance' for 0:Fixnum
from accounts.rb:29:in `debit'
from accounts.rb:29:in `transferToSavings'
from accounts.rb:42
from :0
But if I commented out "ths doesn't works" and remove comments
on "this works" codes, it works. Don't the code
@checking = super(checking)
@savings = super(savings)
create a new 'Account' class instances and stores them into
instance variable of class 'Accounts' @checking and @savings
respectively?
class Account
def initialize(balance)
@balance = balance
end
attr_reader :balance
attr_writer :balance
end
class Accounts < Account
attr_reader :checking, :savings
def initialize(checking, savings)
# these doesn't works
@checking = super(checking)
@savings = super(savings)
# but these works
# @checking = checking
# @savings = savings
end
private
def debit(account, amount)
account.balance -= amount
end
def credit(account, amount)
account.balance += amount
end
public
def transferToSavings(amount)
# private method can be called only in the defining class
debit(@checking, amount)
credit(@savings, amount)
end
end
# this doesn't work
accounts = Accounts.new(0, 10000)
# this works
#accounts = Accounts.new(Account.new(0), Account.new(10000))
accounts.balance # balance is the instance method of class 'Account'
accounts.balance = 100
accounts.checking
accounts.savings
accounts.transferToSavings(100)
accounts.checking
accounts.savings
Thanks a lot
SYLee