How to share variables across my .rb files?

前端 未结 4 1174
轻奢々
轻奢々 2020-12-13 18:20

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

相关标签:
4条回答
  • 2020-12-13 18:56
    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]"
      
    0 讨论(0)
  • 2020-12-13 19:03
    module Foo
      attr_accessor :test_var
      def initialize
        @test_var = "hello world"
      end
    end
    

    Create the module with your variable or variables in your config file and then include the module in whatever class you intend to use.

    require_relative 'foomod.rb'
    class Bar
      include Foo
    end
    
    foobar = Bar.new
    foobar.test_var = "goodbye"
    puts foobar.test_var
    

    Each instance of the class will initialize with whatever value you would like.

    0 讨论(0)
  • 2020-12-13 19:10

    You shouldn't need to wrap these variables in a module.

    Simply adding them to another_file.rb and using require_relative 'another_file' (if it's in the same directory) or require 'path/to/another_file' should be sufficient to share those variables across files.

    0 讨论(0)
  • 2020-12-13 19:11

    Ruby will never share local variables between files. You can wrap them in a Module though:

    module SharedVaribles
      @test_var="Hello, World"
    
      def self.test_var
        return @test_var
      end
    
      def self.test_var=(val)
        @test_val=val;
      end
    end
    

    Put that in settings.rb, require it into all your files, and use SharedVaribles.test_var and SharedVaribles.test_var= to access the variable. Remember, Ruby's require is nothing like C's #include, it is much more complex. It executes the file, then imports all constants, modules, and classes to the requireer.

    0 讨论(0)
提交回复
热议问题