Created
October 1, 2009 04:31
-
-
Save bradgessler/198731 to your computer and use it in GitHub Desktop.
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
arr = [{:a => 1}, {:a => 2}, {:a => 3}, {:a => 4}, {:b => 3}, {:b => 4}, {:a => 5}] | |
# I want to get ... | |
# | |
# [ | |
# {:a => [1,2,3,4]}, | |
# {:b=> [3,4]}, | |
# {:a => [5]} | |
# ] | |
module Enumerable | |
def segment | |
self.inject([]) do |memo, curr_obj| | |
curr_key = yield(curr_obj) | |
prev_key, prev_objs = memo[-1] | |
if curr_key == prev_key | |
prev_objs.push curr_obj | |
else | |
memo.push [curr_key, [curr_obj]] | |
end | |
memo | |
end | |
end | |
end | |
puts arr.segment{|h| h.keys.first }.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment