在 Ruby 中需要另一个文件时停止执行代码

Stop execution of code when requiring another file in Ruby

我有一个文件 foo.rb,其中包含以下内容:

class Foo
    def do_stuff
        puts "Doing stuff"
    end

    def do_other_stuff
        puts "Doing other stuff"
    end
end

f = Foo.new
f.do_stuff

我想在另一个文件 bar.rb 中要求此文件并访问 Foo class 中的方法而不执行 foo.rb 中的指令。 期望只输出:

Doing other stuff

我在 bar.rb 中尝试了以下方法:

require 'foo'

f = Foo.new
f.do_other_stuff

但是,要求文件执行foo.rb的代码,我的输出是这样的:

Doing stuff
Doing other stuff

有什么好办法绕过这次执行吗?

如果您只想阻止输出,请执行以下操作:

stdout_old = $stdout.dup
stderr_old = $stderr.dup
$stderr.reopen(IO::NULL)
$stdout.reopen(IO::NULL)
require "foo"
$stdout.flush
$stderr.flush
$stdout.reopen(stdout_old)
$stderr.reopen(stderr_old)

需要文件将执行代码。我认为这是一个糟糕的设计,你正在努力实现。但是,您仍然可以通过将代码放在 if __FILE__ == [=11=] 块中来规避它:

if __FILE__ == [=10=]
 f = Foo.new
 f.do_stuff
end

if __FILE__ == [=11=] 将确保块内的代码仅在 运行 时直接执行,而不是在需要时执行,如您的示例所示。

I want require this file in another file bar.rb and access to the methods in the Foo class without executing the instructions in foo.rb.

由于Fooclass中的方法是通过执行foo.rb中的指令定义的,这显然是无意义的不可能:要么你想要Foo,那么你必须执行指令,或者你不执行指令,但是你得不到Foo