Skip to content

Instantly share code, notes, and snippets.

@gerow
Created July 1, 2013 18:56
Show Gist options
  • Save gerow/5903544 to your computer and use it in GitHub Desktop.
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.
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