需要文件而不执行代码? [英] Require file without executing code?
问题描述
这里有两个文件:
def method
puts "This won't be outputted."
end
puts "This will be outputted."
main.rb
require "./file"
运行main.rb时,它将在file.rb中加载所有代码,因此我将得到这将被输出".在屏幕上.
When running main.rb it will load all the code inside file.rb so I will get "This will be outputted." on the screen.
是否可以在不运行代码的情况下加载文件?
Is it possible to load a file without having it to run the code?
因为我想加载所有方法(也在模块和类中),而不必执行这些范围之外的代码.
Cause I want to load all the methods (in modules and classes too) without having to execute code outside these scopes.
推荐答案
是否可以在不运行代码的情况下加载文件?
Is it possible to load a file without having it to run the code?
否,ruby文件中的所有内容都是可执行代码,包括类和方法定义(例如,当您尝试在if语句内定义方法时,您会看到此代码,它工作得很好).因此,如果您不执行文件中的任何内容,则不会定义任何内容.
No, everything in a ruby file is executable code, including class and method definitions (you can see this when you try to define a method inside an if-statement for example, which works just fine). So if you wouldn't execute anything in the file, nothing would be defined.
但是,您可以告诉ruby,某些代码仅在直接运行文件时才执行-不需要时才执行.为此,只需将有问题的代码放在if __FILE__ == $0
块中.因此对于您的示例,这将起作用:
You can however tell ruby that certain code shall only execute if the file is run directly - not if it is required. For this simply put the code in question inside an if __FILE__ == $0
block. So for your example, this would work:
def method
puts "This won't be outputted."
end
if __FILE__ == $0
puts "This will not be outputted."
end
main.rb
require "./file"
这篇关于需要文件而不执行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!