Created
November 6, 2012 22:16
-
-
Save kirel/4028011 to your computer and use it in GitHub Desktop.
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
| # returns a ranking as a hash { elem => rank } | |
| # ranks based on the sort order of the values the given block yields | |
| # elements yielding the same value are ranked the same | |
| module Enumerable | |
| def rank_by | |
| inject(Hash.new {|h, k| h[k] = []}) { |h, e| h[yield(e)] << e; h } | |
| .sort.each_with_index | |
| .inject({}) { |h,((_, es), i)| es.each { |e| h.update e => i + 1 }; h } | |
| end | |
| end | |
| if __FILE__ == $0 | |
| require 'rspec/autorun' | |
| describe 'rank_by' do | |
| it 'should rank' do | |
| [1, 2, 3].rank_by(&:to_i).should == { 1 => 1, 2 => 2, 3 => 3 } | |
| [1, 2, 3].rank_by { |i| -i }.should == { 3 => 1, 2 => 2, 1 => 3 } | |
| %w(1 123 2 234 12345).rank_by(&:length).should == { | |
| "1" => 1, | |
| "123" => 2, | |
| "2" => 1, | |
| "234" => 2, | |
| "12345" => 3 | |
| } | |
| %w(wat wat duck).rank_by(&:to_s).should == { 'duck' => 1, 'wat' => 2 } | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment