DEV Community

loading...

Discussion on: Daily Challenge #4 - Checkbook Balancing

Collapse
neotamizhan profile image
Siddharth Venkatesan

Ruby

class Checkbook

  def initialize
    @entries = []
    @balance = 0.0
    @orig_bal = 0.0
    load!
  end

  def total_expense
    @entries.map {|e| e.check_amount}.sum
  end

  def average_expense
    total_expense / @entries.size
  end

  def load!
    content = File.readlines("input.txt")    
    @balance = @orig_bal = content[0].to_f    
    (1..content.size-1).each do |n|
      line = content[n]
      @entries << CheckEntry.new(line)
    end    
    calculate_balance!
  end

  def calculate_balance!
    @entries.sort!  
    @entries.each do |entry|
      #puts "#{@balance} : #{entry.check_amount}"
      @balance -= entry.check_amount
      entry.running_balance = @balance
    end
  end

  def to_s      
    disp = []
    disp << "%.2f" % @orig_bal
    disp << @entries.map {|e| e.to_s}
    disp << "Total Expenses = #{"%.2f" % total_expense}"
    disp << "Average Expenses = #{"%.2f" % average_expense}"

    disp.join("\n")
  end
end

class CheckEntry

  attr_accessor :check_number, :category, :check_amount, :running_balance


  def initialize(line)
    @check_number = 0
    @category = ""
    @check_amount = 0.0
    @running_balance = 0.0    
    load!(line)
  end 

  def load!(line)    
    line = sanitize(line)      
    matches = /^(\d+)\s+(.*?)\s(.*)$/.match(line)
    @check_number = matches[1].to_i
    @category = matches[2]
    @check_amount = matches[3].to_f    
  end

  def sanitize(line)
    line.gsub(/([^\d\w\s\.])/, '')
  end

  def to_s
    "#{@check_number} #{@category} #{"%.2f" % @check_amount} #{"%.2f" % @running_balance}"
  end

   def <=>(other)
    @check_number <=> other.check_number
  end
end

puts Checkbook.new

Output :

1233.00
120 Picture 34.00 1199.00
121 Gasoline 13.60 1185.40
122 Picture 93.50 1091.90
123 Flowers 93.50 998.40
123 Photos 71.40 927.00
124 Gasoline 11.00 916.00
125 Hardware 24.80 891.20
127 Meat 120.90 770.30
129 Stamps 13.60 756.70
129 Fruits 17.60 739.10
129 Market 128.00 611.10
132 Tires 19.00 592.10
Total Expenses = 640.90
Average Expenses = 53.41