A return from inside a block that’s still in scope acts as a return from that scope. A return
from a block whose original context is not longer valid raises an exception (LocalJumpError
or ThreadError depending on the context). The following example illustrates the first case:
引用
def meth1
(1..10).each do |val|
return val # returns from meth1
end
end
meth1 # => 1
This example shows a return failing because the context of its block no longer exists:
def meth2(&b)
b
end
res = meth2 { return }
res.call
produces:
prog.rb:5:in `block in <main>': unexpected return (LocalJumpError)
from /tmp/prog.rb:6:in `call'
from /tmp/prog.rb:6:in `<main>'
And here’s a return failing because the block is created in one thread and called in another:
def meth3
yield
end
t = Thread.new do
meth3 { return }
end
t.join
produces:
prog.rb:6:in `block (2 levels) in <main>': unexpected return (LocalJumpError)
from /tmp/prog.rb:2:in `meth3'
from /tmp/prog.rb:6:in `block in <main>'
The situation with Proc objects is slightly more complicated. If you use Proc.new to create
a proc from a block, that proc acts like a block, and the previous rules apply:
def meth4
p = Proc.new { return 99 }
p.call
puts "Never get here"
end
meth4 # => 99
If the Proc object is created using Kernel.lambda, it behaves more like a free-standing
method body: a return simply returns from the block to the caller of the block:
def meth5
p = lambda { return 99 }
res = p.call
"The block returned #{res}"
end
meth5 # => "The block returned 99"
Because of this, if you use Module#define_method, you’ll probably want to pass it a proc
created using lambda, not Proc.new, because return will work as expected in the former and
will generate a LocalJumpError in the latter.
1.8中Proc.new和lambda的行为是一样的,但在1.9中Proc.new发生改变,所以在新代码尽量不要使用Proc.new,除非你确信你的代码不会运行在1.8的环境中
分享到:
相关推荐
在规则引擎中,Ruby 的闭包使用特别频繁,而且有 block,Proc和 lambda 等后几种形式的用法,很让人困惑。为了深入理解代码,再次认真学习了一下 Ruby 的闭包,特别是 block,proc 和 lambda 几种用法的异同,这次的...
主要介绍了Ruby中proc和lambda的两个区别,本文讲解了在proc和lambda中,return关键字有不同含义、检查参数的方式不同两个重要区别,需要的朋友可以参考下
proc学习proc学习proc学习proc学习proc学习proc学习
Ruby中的闭包实现有:Block,Proc,Lambada。 首先,我们来看Block。 代码如下: ary = [1,2,3,4] ary.collect! do |a| a*a end ary.each do |a| puts a end 这段代码,我们使用了Array对象的block方法,将ary中...
开源项目-jasonmoo-lambda_proc.zip,在go中运行aws lambda函数的伴随进程
proc文件系统讲解,非常详细。 1 收集系统信息 1.0 proc文件系统概览 1.1 进程相关信息子目录 1.2 内核数据 1.3 IDE接口信息 /proc/ide 1.4 网络统计信息 /proc/net 1.5 SCSI接口信息 /proc/scsi 1.6 并行端口信息 /...
proc 文件系统 proc 文件系统 proc 文件系统 proc 文件系统 proc 文件系统
PROC简介 3. 宿主变量与指示变量 4. 嵌入SQL语句
Proc开发文档
oracle proc 经典教程
proc.frm proc.MYD proc.MYI
proc c的程序概述 什么是proc c proc c程序设计的基础知识
ProC Precompiler
使用 proc 文件系统来访问 Linux 内核的内容使用 proc 文件系统来访问 Linux 内核的内容使用 proc 文件系统来访问 Linux 内核的内容使用 proc 文件系统来访问 Linux 内核的内容使用 proc 文件系统来访问 Linux 内核...
提供Oracle ProC程序的开发,详尽的介绍Proc的开发过程
proc的入门学习材料,PROC学习文档,该文档为chm格式,是学习proc的入门资料
linux proc文件系统简介 linux proc文件系统简介
proc编程,makefile编写,显出一个人的在proc下编程的能力,需要好好的掌握利用