如何在我的 .rb 文件中共享变量? [英] How to share variables across my .rb files?

查看:19
本文介绍了如何在我的 .rb 文件中共享变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个 .rb 文件,我想在所有文件中使用相同的变量.假设变量 test_variable = "test" 应该可以从我的所有 .rb 文件中访问.我怎样才能做到这一点?

I have a few .rb files and I want to use the same variables in all of them. Let's say variable test_variable = "test" should be accessible from all my .rb files. How can I achieve that?

我用 test_variable = "test" 创建了 settings.rb 文件,然后在另一个 .rb<中使用了 require 'settings'/code> 文件,但它没有工作.我想使用 require 而不是 load.

I created settings.rb file with test_variable = "test" then used require 'settings' in another .rb file, but it didn't work. I would like to use require not load.

我试图通过在变量名前加上 $ 前缀来使变量成为全局变量,但我仍然得到 未定义的局部变量或方法 'test_variable' for main:Object (NameError).

I tried to make the variable global by prefixing the variable name with $, but I am still getting undefined local variable or method 'test_variable' for main:Object (NameError).

推荐答案

  1. 常量(包括模块和类)被添加到共享的全局环境中:

  1. Constants (which include modules and classes) are added to the shared global environment:

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 中测试):

  • Global variables are also all part of the same environment (tested in 1.8.6, 1.8.7, and 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]"
    

  • 这篇关于如何在我的 .rb 文件中共享变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆