【问题标题】:Cannot get a method instance to function; How to use an Each Do method in ruby?无法让方法实例发挥作用;如何在 ruby​​ 中使用 Each Do 方法?
【发布时间】:2018-08-03 00:16:59
【问题描述】:

我想调用一个特定的方法,以便查看“帐户”的余额。方法是;

 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)'

这将如何实现?

【问题讨论】:

    标签: ruby methods instance


    【解决方案1】:

    my_account = SavingsAccount.new(100) 视为创建一个新帐户,但您要问的是我想查看一个列表 帐户的所有余额。由于每个帐户都有余额,您可以这样做:

       [my_account, other_account].each do |account|
         puts account.balance
       end
    

    我建议将您的 report_balances 方法移到一个类方法或一起移出该类,但这是一个不同的讨论主题。

    【讨论】:

    • 有道理,'每一个'都与数组有关,所以现在我明白我做错了什么谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多