Last active
December 18, 2015 17:09
-
-
Save joshed-io/5816332 to your computer and use it in GitHub Desktop.
Revisions
-
joshed-io revised this gist
Jun 19, 2013 . 1 changed file with 2 additions and 2 deletions.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -19,13 +19,13 @@ ] # flatten the API response into a single hash # e.g. {"Apple"=>15, "Orange"=>10, "Grape"=>5, "Pear"=>7} flat_hash = keen_result.inject({}) { |acc, entry| acc[entry["entry"]] = entry["result"]; acc } # create a 'set', sorted by the entry count # e.g. [["Grape", 5], ["Pear", 7], ["Orange", 10], ["Apple", 15]] sorted_set = flat_hash.sort_by { |entry, count| count } # given an sorted array of pairs, find the index of the pair -
joshed-io created this gist
Jun 19, 2013 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,42 @@ # Example Keen IO API response for a count, grouped by an 'entry' field keen_result = [ { "entry" => "Apple", "result" => 15 }, { "entry" => "Orange", "result" => 10 }, { "entry" => "Grape", "result" => 5 }, { "entry" => "Pear", "result" => 7 } ] # flatten the API response into a single hash # e.g. {"Apple"=>15, "Orange"=>10, "Grape"=>5} flat_hash = keen_result.inject({}) { |acc, entry| acc[entry["entry"]] = entry["result"]; acc } # create a 'set', sorted by the entry count # e.g. [["Grape", 5], ["Orange", 10], ["Apple", 15]] sorted_set = flat_hash.sort_by { |entry, count| count } # given an sorted array of pairs, find the index of the pair # whose value matches the 'entry' param def zrank(entry, set) set.each_with_index { |pair, index| return index if entry == pair[0] } end puts "Apple: #{zrank("Apple", sorted_set)}" #=> 3 puts "Orange: #{zrank("Orange", sorted_set)}" #=> 2 puts "Grape: #{zrank("Grape", sorted_set)}" #=> 0 puts "Pear: #{zrank("Pear", sorted_set)}" #=> 1