proc函数相对于方法有什么优点
我正在解决 Project Euler 上的一些问题,并且我提到我总是将短方法包装在 proc 函数中。我问自己“为什么?”。答案是“我不知道。也许是因为它很短?”。
那么 proc 函数相对于普通方法除了短之外还有什么优点呢:)
# 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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我立即想到的是能够传递它们并将它们存储在数据结构中。我在一个小型命令行解析器中使用后一种情况不太长:使用正则表达式解析用户输入,并使用解析后的字符串的其余部分作为参数调用
commands[command]
。当然,您可以使用方法和发送来执行相同的操作,但恕我直言,命令哈希更好。我有时使用的另一件事——尽管它在 Ruby 中并不常见——是 curry 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 andsend
, 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:EDIT: Here's another example (simplified, no error handling):