Created
April 24, 2014 12:32
-
-
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.
This file contains hidden or 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
| 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