ruby - 从 Ruby 中包含的文件访问变量

标签 ruby include

如何访问包含文件中定义的变量?

# inc.rb
foo = "bar";


# main.rb
require 'inc.rb'
puts foo

# NameError: undefined local variable or method `foo' for main:Object

最佳答案

您无法访问其定义范围之外的本地文件——在本例中为文件。如果您想要跨文件边界的变量,请将它们设为局部变量。 $fooFoo@foo 都可以。

如果你真的不想在符号上放置任何类型的装饰(可能因为你不喜欢它的读法),一个常见的 hack 就是将它定义为一个方法: def foo() "bar"end.

关于ruby - 从 Ruby 中包含的文件访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2854026/

相关文章:

opengl - CMake:opengl 包含目录在不同平台上的命名不同

rust - 如何在 Rust 中正确包含文件?

ruby - 无方法错误 : ruby gem mechanize undefined method 'q= '

ruby-on-rails - 查找在丰富的连接表 rails 中没有关联记录的所有记录

c - : #define, #include, #undef 的目的

php - 在网页上包含外部代码(php include() 或 get_header())

c++ - <> 中包含的文件找不到 ""中包含的文件

Ruby:如何将包含连续字母组的字符串拆分为这些字母组?

ruby-on-rails - 截断 Markdown ?

ruby-on-rails - 在运行时在 Rails 3 中加载 gem