ruby中Block, Proc 和 Lambda 浅析

Block 与Proc的区别:

  Block是代码块,Proc是对象;

  参数列表中最多只能有一个Block, 但是可以有多个Proc或Lambda;

  Block可以看成是Proc的一个类实例.

Proc 与Lambda 区别:

   Proc和Lambda都是Proc对象;

   Lambda检查参数个数,当传递的参数超过一个时,会报错,而Proc不检查,当传递参数多于一个时,只传递第一个参数,忽略掉其他参数;

   Proc和Lambda中return关键字的行为是不同的.

# Block Examples 

[1,2,3].each { |x| puts x*2 } # block is in between the curly braces

[1,2,3].each do |x| puts x*2 # block is everything between the do and end end

# Proc Examples

p = Proc.new { |x| puts x*2 } [1,2,3].each(&p) # The '&' tells ruby to turn the proc into a block 

proc = Proc.new { puts "Hello World" } 

proc.call # The body of the Proc object gets executed when called 

 

# Lambda Examples 

lam = lambda { |x| puts x*2 } 

[1,2,3].each(&lam) 

lam = lambda { puts "Hello World" } 

lam.call

 

# 参数传递

lam = lambda { |x| puts x } # creates a lambda that takes 1 argument

lam.call(2) # prints out 2 lam.call # ArgumentError: wrong number of arguments (0 for 1) 

lam.call(1,2,3) # ArgumentError: wrong number of arguments (3 for 1) 

 

proc = Proc.new { |x| puts x } # creates a proc that takes 1 argument

proc.call(2) # prints out 2

proc.call # returns nil 

proc.call(1,2,3) # prints out 1 and forgets about the extra arguments

# Return行为

# lambda中return跳出lambda,仍然执行lambda外部代码

def lambda_test 

  lam = lambda { return } 

  lam.call puts "Hello world" 

end 

lambda_test # calling lambda_test prints 'Hello World'

def proc_test 

#proc中return直接跳出函数

  proc = Proc.new { return } 

  proc.call 

  puts "Hello world"

end 

proc_test # calling proc_test prints nothing

为了随时查阅,没有侵权意思,望见谅!

文章出处:http://my.oschina.net/u/811744/blog/152802

 

posted @ 2015-12-18 13:12  鞋带松了  阅读(249)  评论(0编辑  收藏  举报