Created
July 1, 2013 18:56
-
-
Save gerow/5903544 to your computer and use it in GitHub Desktop.
I've been using this pattern a lot in ruby, and I was wondering if there's a better way to do this. It kinda feels like its perverting the use of the reduce function when all I really want to do is split a list into a list of lists by a specific field value.
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
def split_list_by list, &block | |
list.reduce({}) {|memo, v| | |
key = yield v | |
memo[key] ||= [] | |
memo[key] << v | |
memo | |
}.map{|k, v| | |
v | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment