Skip to content

Instantly share code, notes, and snippets.

@chrislloyd
Created April 10, 2012 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrislloyd/2355509 to your computer and use it in GitHub Desktop.
Save chrislloyd/2355509 to your computer and use it in GitHub Desktop.
Handy grouping funtion
#!/usr/bin/env ruby
require 'active_support/core_ext'
abort("usage: #{__FILE__} day|week|month") unless %w(day week month).include?(ARGV[0])
$stdin.readlines.map {|l|
timestamp, amount = l.strip.split(',', 2)
[Time.at(timestamp.to_i), amount.to_i]
}.group_by {|(time, _)|
case ARGV[0]
when 'day'
time.beginning_of_day
when 'week'
time.beginning_of_week
when 'month'
time.beginning_of_month
end
}.inject([]) {|results, (period, entries)|
results << [period.strftime("%Y-%m-%d"), entries.inject(0){|total, entry| total += entry[1] }]
results
}.sort_by {|(period, _)|
period
}.each {|row|
puts row.join(',')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment