问题描述
file1
需要file2
,并且我希望能够在特定条件下取消对file2
的评估而不会退出整个过程.
file1
requires file2
, and I want to be able to cancel evaluating file2
under certain conditions without exiting the whole process.
# file1.rb
puts "In file 1"
require 'file2'
puts "Back in file 1"
# file2.rb
puts "In file 2"
# return if some_conditional
puts "Still in file 2"
运行file1
时,我想看到的输出是:
When running file1
, the output I want to see is:
In file 1
In file 2
Back in file 1
目标是从不打印Still in file 2
,而打印Back in file 1
. 在file2
中我可以做些什么吗?
The goal is for Still in file 2
to never print, while Back in file 1
does print. Is there anything I can do in file2
to make this possible?
在这里我不能使用exit
/exit!
/abort
,因为Back in file 1
将永远不会打印.我可以使用raise
/fail
,但是要做到这一点,我必须更改file1
和rescue
失败的require
.我希望找到一种不涉及更改file1
的方法.
I can't use exit
/exit!
/abort
here because Back in file 1
will never print. I could use raise
/fail
, but to do that I would have to change file1
and rescue
the failed require
. I'm hoping to find a way that doesn't involve altering file1
.
更新:
A "top-level return" feature has been added.
推荐答案
更新:
A "top-level return" feature has been added.
原始:
评论员 matt 指出功能4840可以完全满足我的要求自2011年6月以来一直在讨论.此外,此功能还一直在核心团队中进行讨论,直到2015年11月 ,该功能
设计这样的功能会涉及很多困难;有关优缺点的清单,我强烈建议您查看讨论内容.
if condition
return
end
while condition
# ...
return
end
begin
# ...
return
rescue
# ...
return
ensure
# ...
return
end
And it would not exit the required file in the following statements:
class Foo
return # LocalJumpError
end
def foo
return # returns from method, not from required file
end
proc do
return # LocalJumpError
end
x = -> { return } # returns as from lambda, not from required file
由于该功能仍未实现,我将赏金授予 steenslag ,以成功解决该问题(如最初所写)而不是精神.
Since the feature remains unimplemented, I have awarded the bounty to steenslag for successfully solving the problem (as originally written) to the letter, if not the spirit.
这篇关于如何取消评估所需的Ruby文件? (又称顶级回报)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!