如何取消评估所需的 Ruby 文件?(又名顶级回报) [英] How to cancel evaluating a required Ruby file? (a.k.a. top-level return)

查看:18
本文介绍了如何取消评估所需的 Ruby 文件?(又名顶级回报)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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,但要做到这一点,我必须更改 file1rescue 失败的 <代码>要求.我希望找到一种不涉及更改 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 指出 Feature 4840 完全符合我的要求问一下,自 2011 年 6 月开始讨论.此外,核心团队仍在讨论该功能,直到 2015 年 11 月关于 Ruby 新功能的会议.

Commenter matt pointed out that Feature 4840, which would do exactly what I'm asking about, has been in discussion since June 2011. Further, the feature was still being discussed as late as November 2015 in core team meetings regarding new Ruby features.

设计这样的功能有很多困难;对于利弊列表,我强烈建议您查看讨论.

There are a lot of difficulties involved in designing a feature like this; for a list of the pros and cons, I highly suggest checking out the discussions.

提议的功能将允许在使用以下任何顶级语句时退出所需的文件:

The proposed feature would allow exiting the required file while using any of the the following top-level statements:

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 文件?(又名顶级回报)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆