Skip to content

Instantly share code, notes, and snippets.

@tlux
Created April 24, 2014 12:32
Show Gist options
  • Select an option

  • Save tlux/11253041 to your computer and use it in GitHub Desktop.

Select an option

Save tlux/11253041 to your computer and use it in GitHub Desktop.
Enumerable#group_by_first and Enumerable#group_by_last do in contrast du Enumerable#group_by not return an Array on the value side of the hash but only a single element.
module Enumerable
def group_by_first
inject({}) do |hash, element|
key = yield(element)
hash[key] ||= element
hash
end
end
def group_by_last(&block)
reverse.group_by_first(&block)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment