How to share variables across my .rb files?

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

提交回复
热议问题