Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Array#to_proc, shorthand for creating a block that selects elements of an array/hash/collection.
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