如果程序中有require 'helper_file'
,并且在所需文件中声明了常量和变量,是否有办法访问这些变量和常量?
require 'helper_file'
...some nice code
x = ConstantFromRequireFile
答案 0 :(得分:4)
使用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
答案 1 :(得分:2)
在所需文件的顶级作用域中定义的常量,全局变量,实例变量和类变量都将在需求文件的范围内可用,但局部变量不会。究竟是什么问题?