Skip to content

Instantly share code, notes, and snippets.

@justahero
Last active December 9, 2017 12:18
Show Gist options
  • Save justahero/b1dc0386475000dbcd7946a442c53333 to your computer and use it in GitHub Desktop.
Save justahero/b1dc0386475000dbcd7946a442c53333 to your computer and use it in GitHub Desktop.
Example on how to use to_proc with Ruby classes
# class to test behaviour of Proc and to_proc
class ProcTest
def initialize(text='')
@text = text
end
def say
puts "say #{text}"
end
attr_reader :text
def to_proc
->(obj, *args) { obj.send(self, *args) }
end
def self.to_proc
->(*args) { new(*args) }
end
end
# initial list of strings
list = ["hello", "json", "how", "are", "you"]
# create instances of ProcTest, each string used as argument, using Test.to_proc
list.map(&ProcTest)
# create instances of ProcTest and call on each instance the 'say' method, invoking Test#to_proc
list.map(&ProcTest).map(&:say)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment