Created
April 15, 2015 15:29
-
-
Save jferris/05de6194f5ccd70e84f1 to your computer and use it in GitHub Desktop.
Partially applied instance methods in Ruby
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 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