我如何使用注入方法来计算平衡而不是现在的平衡?

时间:2015-02-06 16:22:11

标签: ruby

在平衡功能中,我试图使用注入方法来计算余额。尝试了文档,但无法得到它..

我是Ruby和编程的新手,所以任何帮助都会受到赞赏..

class BankAccount
      attr_reader :name

      def initialize(name)
        @name = name
        @transactions = []
        add_transaction("Beginning Balance", 0)
      end

      def credit(description, amount)
        add_transaction(description, amount)
      end

      def debit(description, amount)
        add_transaction(description, -amount)
      end

      def add_transaction(description, amount)
        @transactions.push(description: description, amount: amount)
      end

      def balance
        balance = 0.0
        @transactions.each do |transaction|
          balance += transaction[:amount]
        end
        return balance
      end

      def to_s
        "Name: #{name}, Balance: #{sprintf("%0.2f", balance)}"
      end

      def print_register
        puts "#{name}'s Bank Account"
        puts "-" * 40

        puts "Description".ljust(30) + "Amount".rjust(10)
        @transactions.each do |transaction|
          puts transaction[:description].ljust(30) + sprintf("%0.2f", transaction[:amount]).rjust(10)
        end

        puts "-" * 40
        puts "Balance:".ljust(30) + sprintf("%0.2f", balance).rjust(10)
        puts "-" * 40
      end

    end

1 个答案:

答案 0 :(得分:1)

你的例子很棒,因为你可以很容易地改变注入呼叫的循环:

def balance
  @transactions.inject(0.0) { |balance, transaction| balance + transaction[:amount] }
end