我有一些.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中声明的实例变量都是同一main的一部分:
    phrogz$ cat instance1.rb
    @test_variable = "test"
    
    phrogz$ cat instance2.rb
    require_relative 'instance1'
    p @test_variable
    
    phrogz$ ruby instance2.rb
    "test"
    
  • 全局变量也都是同一环境的一部分(在1.8.6、1.8.7和1.9.2中进行了测试):
    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/

    10-09 02:03
    查看更多