Skip to content

Instantly share code, notes, and snippets.

@jack-nie
Forked from geowy/array_to_proc.rb
Last active September 10, 2015 05:20
Show Gist options
  • Save jack-nie/e30d80344ece3871a4f2 to your computer and use it in GitHub Desktop.
Save jack-nie/e30d80344ece3871a4f2 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