Skip to content

Instantly share code, notes, and snippets.

@headius
Created September 18, 2011 21:52
Show Gist options
  • Save headius/1225596 to your computer and use it in GitHub Desktop.
Save headius/1225596 to your computer and use it in GitHub Desktop.
Partial application that works on all Ruby implementations
class Object
def _(name, *partial_args)
Proc.new do |*new_args|
send name, *partial_args.map {|arg| arg == :_ ? new_args.shift : arg}
end
end
end
# Practical examples:
[1,2,3].each &_(:puts, :_)
#=> 1\n2\n3\n
[:send, :puts].select &'foo'._(:respond_to?, :_, false)
#=> [:send]
class Object
def _(name, *partial_args)
identifier = "a"
spreads = []
partials = []
params = partial_args.map do |arg|
if arg == :_
partials << identifier
spreads << "_"
else
spreads << identifier
end
(result, identifier = identifier, identifier.succ)[0]
end
eval <<-PROC
#{spreads.join(',')} = partial_args
Proc.new do |#{partials.join(',')}|
#{name}(#{params.join(',')})
end
PROC
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment