Skip to content

Instantly share code, notes, and snippets.

@estum
Last active August 29, 2015 14:19
Show Gist options
  • Save estum/50c1f10bcfb97fa9fa15 to your computer and use it in GitHub Desktop.
Save estum/50c1f10bcfb97fa9fa15 to your computer and use it in GitHub Desktop.
Array#to_proc: quick iterate chaining calls like .map(&[...])
unless Array.method_defined?(:to_proc)
class Array
# Converts array to proc with chained calls of items.
# Every item can be either a method name or an array with
# a method name and args.
#
# ==== Examples
#
# the_hash = { :one => "One", :two => "Two", :three => 3, :four => nil }
# mapping = { "one" => "1", "two" => "2", "" => "0" }
#
# the_hash.select(&[[:[], 1], [:is_a?, String]])
# # => { :one => "One", :two => "Two" }
#
# the_hash.values.map(&[:to_s, :downcase, [:sub, /one|two|$^/, mapping]])
# # => ["1", "2", "3", "0"]
#
# :call-seq:
# [].to_proc
# &[:method1, [:method2, *args], [:method3, ...]]
def to_proc
proc do |*obj|
obj = obj.shift if obj.size == 1
reduce(obj) do |chain, sym|
chain.public_send(*Array(sym).flatten)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment