如果我在程序中需要“helper_file”
,并且在该所需文件中声明了常量和变量,有没有办法访问这些变量和常量?
需要'helper_file'
...一些不错的代码
x = ConstantFromRequireFile
最佳答案
您使用 require 将库加载到您的 Ruby 程序中。如果成功,它将返回 true。
所以你有一个文件example.rb:
require 'library.rb'
# Some code
x = CONSTANTFROMREQUIREFILE
puts x # "Hello World"
method_from_required_file # "I'm a method from a required file."
和一个文件library.rb:
CONSTANTFROMREQUIREFILE = "Hello World"
def method_from_required_file
puts "I'm a method from a required file."
end
如您所见,您可以像访问同一文件中的常量和方法一样访问常量和方法。
您可以在这里阅读更多关于 require 的信息:What is the difference between include and require in Ruby?在这里:Kernal Module in Ruby
关于ruby - 访问 'required' 文件的范围以获取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7716634/