What are the advantages of proc functions to methods

坚强是说给别人听的谎言 提交于 2019-12-05 21:48:40

Being able to pass them around and to store them in data structures is something that immediately comes to mind. I used the latter case not too long in a small command line parser: parse user input with a regex and call commands[command] with the rest of the parsed string as arguments. Sure, you could do the same with methods and send, but IMHO the commands hash is nicer. Another thing I sometimes use — even though it's not really common in Ruby — is to curry procs, which you can't really do with a method:

>> multiplier = proc { |x, y| x * y }
=> #<Proc:0x00000100a158f0@(irb):1>
>> times_two = multiplier.curry[2]
=> #<Proc:0x00000100a089c0>
>> times_two[5]
=> 10

EDIT: Here's another example (simplified, no error handling):

 commands = { :double => proc { |x| x * 2 }, :half => proc { |x| x / 2 } }
 run_command = proc do 
     command, arg = STDIN.gets.split 
     commands[command.intern][arg.to_i]
 end
 run_command.call
 half 10
 # => 5
 run_command[]
 double 5
 # => 10
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!