mileage.rb
  1| #!/usr/local/bin/ruby
  2| 
  3| class FillupList
  4|   attr :max_fuel
  5|   attr :max_distance
  6|   attr :max_mileage
  7|   attr :min_mileage
  8|   attr :max_price
  9|   attr :min_price
 10| 
 11|   def initialize
 12|     @fillups = Array.new
 13|     @max_fuel = @max_distance = @max_mileage = @max_price = 0
 14|     @min_mileage = @min_price = 9999 # big number
 15|   end
 16| 
 17|   def append(fillup)
 18|     @fillups.push(fillup)
 19|     if @max_fuel < fillup.gallons then @max_fuel = fillup.gallons end
 20|     if @max_distance < fillup.distance then @max_distance = fillup.distance end
 21|     if @max_mileage < fillup.mileage then @max_mileage = fillup.mileage end
 22|     if @max_price < fillup.price then @max_price = fillup.price end
 23|     if fillup.mileage < @min_mileage then @min_mileage = fillup.mileage end
 24|     if fillup.price < @min_price then @min_price = fillup.price end
 25|     self
 26|   end
 27| 
 28|   def avg_mileage
 29|     @sum = 0
 30|     @fillups.each { |f| @sum += f.mileage }
 31|     @sum / @fillups.length
 32|   end
 33| 
 34|   def length
 35|     @fillups.length
 36|   end
 37| end
 38| 
 39| class Fillup
 40|   attr :date
 41|   attr :gallons
 42|   attr :distance
 43|   attr :price
 44|   attr :mileage
 45| 
 46|   def initialize(date, gallons, distance, price)
 47|     @date     = date
 48|     @gallons  = gallons
 49|     @distance = distance
 50|     @price    = price
 51|     @mileage  = @distance / @gallons
 52|   end
 53|   
 54|   def to_s
 55|     "Date: #{@date}, Gallons: #{@gallons}, Distance: #{@distance}, " +
 56|       "Price: #{@price}"
 57|   end
 58| end
 59| 
 60| ARGV.each { |name|
 61|   file = File.new(name, "r")
 62|   puts "Mileage for " + name
 63|   list = FillupList.new
 64|   file.each_line { |i|
 65|     if i !~ /^\#/ then
 66|       a = Array.new(i.split(/\s+/))
 67|       b = Fillup.new(a[0], a[1].to_f, a[2].to_f, a[3].to_f)
 68|       list.append(b)
 69|     end
 70|   }
 71|   puts "\tMax fuel:            " + list.max_fuel.to_s
 72|   puts "\tMax distance:        " + list.max_distance.to_s
 73|   printf("\tAvg/min/max mileage: %.3f/%.3f/%.3f\n",
 74|          list.avg_mileage, list.min_mileage, list.max_mileage)
 75|   puts "\tMin/max price:       " + list.min_price.to_s + '/' +
 76|     list.max_price.to_s
 77|   puts "\tCount of recorded fillups: " + list.length.to_s
 78|   file.close
 79| }