How to share variables across my .rb files?

前端 未结 4 1191
轻奢々
轻奢々 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 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.

提交回复
热议问题