Proc.new , proc , lambda and "store values of local variables within the scope in which the block was created"

简介:
Proc.new, proc, lambda 用于从block创建对象.
Ruby 1.8 中 , proc, lambda 都需要检查参数个数. Proc.new 不检查参数个数.
Ruby 1.9 中 , lambda 需要检查参数个数. Proc.new和proc 不检查参数个数.
block中调用的本地变量, 取自创建这个块时所在的本地变量, 而不是调用块时的本地变量.
下面都是Ruby 1.9 中的举例,
 举例一 :
x = "hello world"
ablock = lambda{ |y| puts(x) }  
# 如果上面这行改成 ablock = lambda{ puts(x) }, 调用ablock都将报错, wrong number of arguments (1 for 0 (ArgumentError)
def aMethod(ablockArg)
  x = "goodbye"
  ablockArg.call(x)
end

puts(x) #=> "hello world"
ablock.call(x) #=> "hello world"
aMethod(ablock) #=> "hello world"
ablock.call(x) #=> "hello world"
puts(x) #=> "hello world"
输出都是 "hello world" 没有一个是goodbye, 原因是 " block中调用的本地变量, 取自创建这个块时所在的本地变量, 而不是调用块时的本地变量. "
AI 代码解读


 举例二 : 
x = "hello world"
ablock = proc{ puts(x) }
# proc 在1.9版本中不用检查参数个数, 所以不会报错
def aMethod(ablockArg)
  x = "goodbye"
  ablockArg.call(x)
end

puts(x) #=> "hello world"
ablock.call(x) #=> "hello world"
aMethod(ablock) #=> "hello world"
ablock.call(x) #=> "hello world"
puts(x) #=> "hello world"
AI 代码解读


 举例三 :
x = "hello world"
ablock = Proc.new{ puts(x) }
Proc.new创建的块对象在调用是也不用检查传入的参数个数.
def aMethod(ablockArg)
  x = "goodbye"
  ablockArg.call(x)
end

puts(x) #=> "hello world"
ablock.call(x) #=> "hello world"
aMethod(ablock) #=> "hello world"
ablock.call(x) #=> "hello world"
puts(x) #=> "hello world"
AI 代码解读


 举例四 : 

严格来说, 上面的代码应该改成如下 :
x = "hello world"
ablock = lambda{ || puts(x) } # 表示不需要传入参数
# 或者 ablock = proc{ || puts(x) }
# 或者 ablock = Proc.new{ || puts(x) }
def aMethod(ablockArg)
  x = "goodbye"
  ablockArg.call()
end

puts(x) #=> "hello world"
ablock.call() #=> "hello world" # 调用时没有传入参数, 所以检查参数个数时是正确的.
aMethod(ablock) #=> "hello world"
ablock.call() #=> "hello world"
puts(x) #=> "hello world"
AI 代码解读


目录
打赏
0
0
0
0
20693
分享
相关文章
InvalidJobConfException: Output directory not set
InvalidJobConfException: Output directory not set
87 0
MGA (Managed Global Area) Reference Note (Doc ID 2638904.1)
MGA (Managed Global Area) Reference Note (Doc ID 2638904.1)
389 0
torch.distributed.init_process_group(‘gloo’, init_method=‘file://tmp/somefile’, rank=0, world_size=1
torch.distributed.init_process_group(‘gloo’, init_method=‘file://tmp/somefile’, rank=0, world_size=1
633 0
torch.distributed.init_process_group(‘gloo’, init_method=‘file://tmp/somefile’, rank=0, world_size=1
ORA-1652: unable to extend temp segment by 128 in tablespace xxx Troubleshootin
当收到告警信息ORA-01652: unable to extend temp segment by 128 in tablespace xxxx 时,如何Troubleshooting ORA-1652这样的问题呢? 当然一般xxx是临时表空间,也有可能是用户表空间。
2131 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等