Created
July 9, 2012 09:38
-
-
Save elado/3075358 to your computer and use it in GitHub Desktop.
Some Ruby Array methods
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
class Array | |
def pinject(memo, &block) | |
inject(memo) { |all, curr| block.call(all, curr); all } | |
end | |
def hash_by | |
return {} unless block_given? | |
pinject({}) { |all, curr| | |
# yield = block to extract key from an item | |
key = yield(curr) | |
all[key] = curr if key | |
} | |
end | |
def grouped_hash_by | |
return {} unless block_given? | |
pinject({}) { |all, curr| | |
# yield = block to extract key from an item | |
(all[yield(curr)] ||= []) << curr | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment