proc函数对方法有什么好处 [英] What are the advantages of proc functions to methods

查看:62
本文介绍了proc函数对方法有什么好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决 Project Euler 上的一些问题,我提到我总是在proc函数中包装简短的方法.我问自己"为什么?".答案是"我不知道.也许是因为它很短?".

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?".

那么proc函数对普通方法的好处是什么,除了它们很短:)

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

推荐答案

能够传递它们并将它们存储在数据结构中是立即想到的事情.我在小型命令行解析器中使用后一种情况的时间不太长:使用正则表达式解析用户输入,并使用解析后的字符串的其余部分作为参数调用commands[command].当然,您可以对方法和send执行相同的操作,但是恕我直言,命令哈希更好.我有时使用的另一种方法-即使在Ruby中并不是很常见-是咖喱 procs,您实际上无法使用以下方法来做到这一点:

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

这是另一个示例(简化,没有错误处理):

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

这篇关于proc函数对方法有什么好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆