Skip to content

Instantly share code, notes, and snippets.

@geowy
Last active September 16, 2015 12:19
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save geowy/39fde25ec2966f90a54b to your computer and use it in GitHub Desktop.
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.
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