我有一些.rb
文件,并且我想在所有文件中使用相同的变量。假设应该从我的所有test_variable = "test"
文件中访问.rb
变量。我该如何实现?
我用settings.rb
创建了test_variable = "test"
文件,然后在另一个require 'settings'
文件中使用了.rb
,但没有用。我想使用require
而不是load
。
我试图通过在变量名前添加$
来使变量成为全局变量,但仍在获取undefined local variable or method 'test_variable' for main:Object (NameError)
。
最佳答案
phrogz$ cat constants1.rb
TEST_VARIABLE = "test"
phrogz$ cat constants2.rb
require_relative 'constants1'
p TEST_VARIABLE
phrogz$ ruby constants2.rb
"test"
main
的一部分:phrogz$ cat instance1.rb
@test_variable = "test"
phrogz$ cat instance2.rb
require_relative 'instance1'
p @test_variable
phrogz$ ruby instance2.rb
"test"
phrogz$ cat global1.rb
$test_variable = "test"
phrogz$ cat global2.rb
require_relative 'global1'
p $test_variable, RUBY_DESCRIPTION
phrogz$ ruby global2.rb
"test"
"ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-darwin10.7.0]"
关于ruby - 如何在我的.rb文件中共享变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8334684/