ruby中Block, Proc 和 Lambda 的区别


Block 与Proc的区别: ruby

  Block是代码块,Proc是对象; curl

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

  Block能够当作是Proc的一个类实例. url

Proc 与Lambda 区别: spa

   Proc和Lambda都是Proc对象; 对象

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

   Proc和Lambda中return关键字的行为是不一样的.
get

# Block Examples  it

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

[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

相关文章
相关标签/搜索