What is Proc
-
Proc
object are blocks of that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables. - Everything in Ruby is an object, but Ruby blocks are not objects. Blocks are not objects, but you can turn them into objects without too much trouble, just wrapping block in an instance of the
Proc
class, since it turns block into afirst class function
, which in turn allows Ruby to support closures and once a language has closures, you can do all sorts of interesting things like making use of various functional concepts.
There is five way to create a Proc object
-
Using
Proc.new
. This is the standard way to create any object, you simple need to pass in a block and you will get back a Proc object which will run the code in the block when you invoke its call method.proc_object = Proc.new {puts "I am a proc object"} proc_object.call # output I am a proc object
-
Using the proc method in the Kernel module.
proc_object = proc {puts "Hello from inside the proc"} proc_object.call # output Hello from inside the proc
-
Using the Kernel lambda method.
proc_object = lambda {puts "Hello form inside the proc"} proc_object.call # output Hello from inside the proc
-
The implicit way.
def my_method puts "hello method" yield end my_method {puts "hello block"} my_method # output hello method hello block hello method [error] in`my_method`: no block given (yield) (LocalJumpError)...
def my_method(&my_block) puts "hello method" my_block.call my_block end block_var = my_method {puts "hello block"} block_var.call # output hello method hello block hello block
Difference between proc and lambda
-
It is important to mention that proc and lambda are both Proc objects.
proc = proc {puts "hello world"} lam = lambda {puts "hello world"} proc.class # returns 'Proc' lam.class # returns 'Proc'
However, lambdas are a different ‘flavor’ or proc.
-
Below are the key differences.
lambdas check the number of arguments, while proc do not
lambdas and proc treat the
return
keyword differently
-
return
inside of a lambda triggers the code right outside of the lambda code -
return
inside of a proc triggers the code outside of the method where the proc is being executed
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。