Skip to content

Instantly share code, notes, and snippets.

@6ewis
Created January 24, 2014 09:03
Show Gist options
  • Save 6ewis/0a1e907d702552707220 to your computer and use it in GitHub Desktop.
Save 6ewis/0a1e907d702552707220 to your computer and use it in GitHub Desktop.
rb:6:in `<class:Parser>': uninitialized constant Parser::Printer (NameError) from parse_energy_data.rb:5:in `<main>'
#/usr/bin/env ruby -w
#Usage parse <argument>
require 'csv'
class Parser
include Printer
attr_accessor :statistics
def initialize filename
self.statistics = {}
deserialize_users filename
print_statistics
end
def deserialize_users filename
CSV.foreach(filename, col_sep: "|", headers: true) do |row|
calculate_statistics(row)
end
end
private
def calculate_statistics row
statistics[:nbr_of_readings] += 1
statistics[:list_of_unique_customers] = []
if !list_of_unique_customers.includes?(:cust_id)
statistics[:list_of_unique_customers] << row[:cust_id]
statistics[:nbr_of_unique_customers] += 1
end
statistics[:nbr_customers_with_electricity] += 1 if row[:elect_or_gas] == 1
statistics[:nbr_customers_with_gas] += 1 if row[:elect_or_gas] == 2
avg_consumption_month row[:bill_month]
end
def avg_consumption_month month
statistics[:"avg_consumption_#{month}"] += row[:consumption]
statistics[:"nbr_of_#{month}_bill_month"] += 1
statistics[:"avg_consumption_#{month}"] /= statistics[:"nbr_of_#{month}_bill_month"]
statistics[:avg_total_consumption] += statistics[:"avg_consumption_#{month}"]
statistics[:nbr_of_total_bill_month] += 1
statistics[:avg_total_consumption] /= statistics[:nbr_of_total_bill_month]
end
end
module Printer
def print_statistics
puts "number of readings: #{statistics[:nbr_of_readings]}"
[:nbr_of_unique_customers, :nbr_customers_with_electricity, :nbr_customers_with_gas].each do |meth|
puts "number of #{meth.to_s.humanize}: #{statistics[meth] }"
end
puts "AVERAGE CONSUMPTIONS".center(26,"-")
Date::MONTHNAMES.compact.each do |month|
puts "%10s %10d" % ["month (all years)", statistics[:"avg_consumption_#{month.downcase}"]]
end
end
end
Parser.new argv[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment