Created
September 18, 2011 21:52
-
-
Save headius/1225596 to your computer and use it in GitHub Desktop.
Partial application that works on all Ruby implementations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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