Skip to content

Instantly share code, notes, and snippets.

@afiore
Last active December 20, 2015 10:59
Show Gist options
  • Save afiore/6120093 to your computer and use it in GitHub Desktop.
Save afiore/6120093 to your computer and use it in GitHub Desktop.
Better currying for Ruby Proc objects
class Proc
def _(*args)
CurriedProc.new(args, &self)
end
end
class CurriedProc < Proc
def initialize(args, &block)
msg = "Curried arguments is greater than block arity (#{args.size} > #{block.arity})"
raise ArgumentError, msg if args.size > block.arity
@curried_args = args
@orig_arity = block.arity
@orig_proc = block
end
def arity
@orig_arity - @curried_args.size
end
def call(*args)
msg = "Wrong number of arguments (#{args.size} of #{arity}) - curried"
raise ArgumentError, msg if args.size > arity
new_args = @curried_args + args.take(arity)
@orig_proc.call(*new_args)
end
def _(*args)
self.class.new(@curried_args + args, &@orig_proc)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment