无法使方法实例运行;如何在ruby中使用Each Do方法?
Cannot get a method instance to function; How to use an Each Do method in ruby?
我想调用一个特定的方法,以便我可以查看 'accounts' 的余额。方法是;
def report_balances(accounts)
accounts.each do |account|
puts account.balance
end
end
我不确定,但我可能错误地构建了上述方法,或者我错误地调用了它,或者我可能在我的代码中正确地放置了该方法。
class BankAccount
attr_reader :balance
def initialize(balance)
@balance = balance
end
def deposit(amount)
@balance += amount if amount >= 0
end
def withdraw(amount)
@balance -= amount if @balance >= amount
end
end
class SavingsAccount < BankAccount
attr_reader :number_of_withdrawals
APY = 0.0017
def initialize(balance)
super(balance) # calls the parent method
@number_of_withdrawals = 0 # then continues here
end
def end_of_month_closeout
if @balance > 0
interest_gained = (@balance * APY) / 12
@balance += interest_gained
end
@number_of_withdrawals = 0
end
def report_balances(accounts)
accounts.each do |account|
puts account.balance
end
end
end
我想查看对象的余额:
my_account = SavingsAccount.new(100)
和
account = BankAccount.new(2500)
通过调用
'report_balances(accounts)'
这将如何实现?
将 my_account = SavingsAccount.new(100)
视为创建一个新帐户,但您要问的是我想查看 列表 帐户的所有余额。由于每个帐户都有余额,您可以这样做:
[my_account, other_account].each do |account|
puts account.balance
end
我建议将您的 report_balances
方法移至 class 方法或从 class 中移出,但这是另一个讨论的主题。
我想调用一个特定的方法,以便我可以查看 'accounts' 的余额。方法是;
def report_balances(accounts)
accounts.each do |account|
puts account.balance
end
end
我不确定,但我可能错误地构建了上述方法,或者我错误地调用了它,或者我可能在我的代码中正确地放置了该方法。
class BankAccount
attr_reader :balance
def initialize(balance)
@balance = balance
end
def deposit(amount)
@balance += amount if amount >= 0
end
def withdraw(amount)
@balance -= amount if @balance >= amount
end
end
class SavingsAccount < BankAccount
attr_reader :number_of_withdrawals
APY = 0.0017
def initialize(balance)
super(balance) # calls the parent method
@number_of_withdrawals = 0 # then continues here
end
def end_of_month_closeout
if @balance > 0
interest_gained = (@balance * APY) / 12
@balance += interest_gained
end
@number_of_withdrawals = 0
end
def report_balances(accounts)
accounts.each do |account|
puts account.balance
end
end
end
我想查看对象的余额:
my_account = SavingsAccount.new(100)
和
account = BankAccount.new(2500)
通过调用
'report_balances(accounts)'
这将如何实现?
将 my_account = SavingsAccount.new(100)
视为创建一个新帐户,但您要问的是我想查看 列表 帐户的所有余额。由于每个帐户都有余额,您可以这样做:
[my_account, other_account].each do |account|
puts account.balance
end
我建议将您的 report_balances
方法移至 class 方法或从 class 中移出,但这是另一个讨论的主题。