Created
May 17, 2011 15:18
-
-
Save martinos/976669 to your computer and use it in GitHub Desktop.
Stats module for thor
This file contains hidden or 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
| module Count | |
| def count_by | |
| self.inject({}) do |memo, elem| | |
| key = yield elem | |
| memo[key] ||= 0 | |
| memo[key] += 1 | |
| memo | |
| end | |
| end | |
| end | |
| class Stats < Thor | |
| desc :stats, "Calculates the basic stats for stdin" | |
| def stats | |
| STDIN.inject({:count => 0, :min => nil, :max => nil, :sum => 0}) do |stats, line| | |
| num = line.to_f | |
| stats[:min] ||= num | |
| stats[:max] ||= num | |
| stats[:min] = num if num < stats[:min] | |
| stats[:max] = num if num > stats[:max] | |
| stats[:sum] += num | |
| stats[:count] += 1 | |
| puts stats.to_yaml | |
| end | |
| end | |
| desc :count_by, "Count number of occurence of the same line content" | |
| def count_by | |
| STDIN.extend(Count) | |
| counts = STDIN.count_by do |line| | |
| line.chomp | |
| end | |
| puts counts.to_yaml | |
| puts "Total: #{counts.inject{|sum,(key, value)| sum += value;sum}}" | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment