Last active
September 16, 2015 12:19
-
-
Save geowy/39fde25ec2966f90a54b to your computer and use it in GitHub Desktop.
Array#to_proc, shorthand for creating a block that selects elements of an array/hash/collection.
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
class Array | |
# Returns a proc which calls [] with the array's contents as arguments | |
# | |
# ====Usage | |
# [[1, 2], [3, 4], [5, 6]].map(&[0]) | |
# # => [1, 3, 5] | |
# | |
# [{ hello: 'world' }, { hello: 'sun', goodbye: 'moon' }].map(&[:hello]) | |
# # => ['world', 'sun'] | |
# | |
# [[1, 2, 3, 4], [5, 6, 7]].map(&[1..-1]) | |
# # => [[2, 3, 4], [6, 7]] | |
def to_proc | |
Proc.new { |obj| obj[*self] } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment