Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

ruby - How to share variables across my .rb files?

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?

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.

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  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"
    
  2. Instance variables declared in main are all part of the same main:

    phrogz$ cat instance1.rb 
    @test_variable = "test"
    
    phrogz$ cat instance2.rb 
    require_relative 'instance1'
    p @test_variable
    
    phrogz$ ruby instance2.rb 
    "test"
    
  3. 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]"
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...