Skip to content

Instantly share code, notes, and snippets.

@padde
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save padde/b706f851f00e84ffd7de to your computer and use it in GitHub Desktop.
Save padde/b706f851f00e84ffd7de to your computer and use it in GitHub Desktop.
Proc#with – Partial Application
require 'forwardable'
class Proc
def with(*arguments, &block)
proc do |*remaining_arguments|
call(*remaining_arguments, *arguments, &block)
end
end
end
class Method
extend Forwardable
def_delegator :to_proc, :with
end
class Symbol
extend Forwardable
def_delegator :to_proc, :with
end
@padde
Copy link
Author

padde commented Jan 12, 2015

Usage with Proc is a bit like "reverse currying"

f = ->(a, b, c) { (a + b) * c }

[1, 2, 3].map(&f.with(3, 2))
#=> [8, 10, 12]

The other methods are just convenience wrappers for Symbol

['foo', 'bar', 'baz'].map(&:center.with(10, '-'))
#=> ["---foo----", "---bar----", "---baz----"]

and Method objects

def piratize(string, seriousness: 3)
  "#{string} arr#{'r'*seriousness}!"
end

['foo', 'bar', 'baz'].map(&method(:piratize).with(seriousness: 4))
#=> ["foo arrrrrr!", "bar arrrrrr!", "baz arrrrrr!"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment