Created
April 10, 2012 23:14
-
-
Save chrislloyd/2355509 to your computer and use it in GitHub Desktop.
Handy grouping funtion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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