Ruby中的Proc,Block的应用说明 - 机器人 - 帮我点击一下google的广告,好吗?赚钱上网 - JavaEye技术网站
Eli Bendersky’s website » Blog Archive » Understanding Ruby blocks, Procs and methods
- Procs play the role of functions in Ruby. It is more accurate to call them function objects, since like everything in Ruby they are objects. Such objects have a name in the folklore - functors. A functor is defined as an object to be invoked or called as if it were an ordinary function, usually with the same syntax, which is exactly what a Proc is.
- Actually, there are two slight differences between
lambdaandProc.new. First, argument checking. The Ruby documentation forlambdastates: Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.. Here is an example to demonstrate this: - lamb = lambda {|x, y| puts x + y}
pnew = Proc.new {|x, y| puts x + y}
# works fine, printing 6
pnew.call(2, 4, 11)
# throws an ArgumentError
lamb.call(2, 4, 11) - Second, there is a difference in the way returns are handled from the Proc. A
returnfromProc.newreturns from the enclosing method (acting just like areturnfrom a block, more on this later): - def try_ret_procnew
ret = Proc.new { return "Baaam" }
ret.call
"This is not reached"
end
# prints "Baaam"
puts try_ret_procnew While
returnfromlambdaacts more conventionally, returning to its caller:- def try_ret_lambda
ret = lambda { return "Baaam" }
ret.call
"This is printed"
end
# prints "This is printed"
puts try_ret_lambda - With this in light, I would recommend using
lambdainstead ofProc.new, unless the behavior of the latter is strictly required. In addition to being way cooler a whopping two characters shorter, its behavior is less surprising.
Posted from Diigo. The rest of my favorite links are here.
没有评论:
发表评论