ruby - 访问 'required' 文件的范围以获取变量

标签 ruby

如果我在程序中需要“he​​lper_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/

相关文章:

ruby-on-rails - Ruby Sort ActiveRecord - float 像 float 一样存储为字符串

ruby |设计数学?

ruby - 使用 ruby​​ 捕获 gdb 输出

ruby - 为什么 if (a,b = [nil, nil]) 在 Ruby 中是真实的?

ruby-on-rails - Rails 替代 Django 管理面板/CRUD View 生成器?

ruby - 你如何过滤 Ruby Find.find() 结果?

ruby-on-rails - bash :/home/XXX/. rvm/scripts/rvm: 没有那个文件或目录

mysql - 如何处理数据以避免 MySQL "incorrect string value"错误?

ruby - Rails 错误:开发环境中的 ActionView::Template::Error(权限被拒绝 @ sys_fail2)

Ruby.exe 仅使用 25% CPU 资源