Skip to content

Instantly share code, notes, and snippets.

@jferris
Created April 15, 2015 15:29
Show Gist options
  • Save jferris/05de6194f5ccd70e84f1 to your computer and use it in GitHub Desktop.
Save jferris/05de6194f5ccd70e84f1 to your computer and use it in GitHub Desktop.
Partially applied instance methods in Ruby
class User
def initialize(name)
@name = name
end
def greet(greeting, info)
"#{greeting}, #{@name}! FYI, #{info}."
end
end
class PartiallyAppliedMethod
def initialize(name, arguments)
@name = name
@arguments = arguments
end
def to_proc
lambda { |instance| instance.public_send(@name, *@arguments) }
end
def call(*arguments)
to_proc.call(*arguments)
end
def |(argument)
PartiallyAppliedMethod.new(@name, @arguments + [argument])
end
end
class Symbol
def |(argument)
PartiallyAppliedMethod.new(self, [argument])
end
end
users = [User.new("Dave"), User.new("Sally"), User.new("Dan")]
puts users.map(&:greet | "Hello" | "it's Wednesday")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment