What are the advantages of proc functions to methods

冷暖自知 提交于 2019-12-14 00:33:45

问题


I was solving some problems on Project Euler and I mentioned that I always wrap short methods in proc functions. I asked myself "Why?". The answer was "I don't know. Maybe because it is short?".

So what are the advantages of proc functions to ordinary methods except that they are short :)

# Proc
is_prime = proc{|number| !((number%2 == 0) || (3..Math.sqrt(number).to_i).step(2).any?{|n| (number%n).zero?})}

# Ordinary method
def is_prime(number)
  !((number%2 == 0) || (3..Math.sqrt(number).to_i).step(2).any?{|n| (number%n).zero?})
end

回答1:


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


来源:https://stackoverflow.com/questions/7106509/what-are-the-advantages-of-proc-functions-to-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!