Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.