Last active
December 9, 2017 12:18
-
-
Save justahero/b1dc0386475000dbcd7946a442c53333 to your computer and use it in GitHub Desktop.
Example on how to use to_proc with Ruby classes
This file contains hidden or 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 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