Create module variables in Ruby

前端 未结 4 604
闹比i
闹比i 2020-12-07 13:33

Is there any way to create a variable in a module in Ruby that would behave similar to a class variable? What I mean by this is that it would be able to be accessed without

4条回答
  •  醉梦人生
    2020-12-07 14:31

    If you do not need to call it from within an instance, you can simply use an instance variable within the module body.

    module SomeModule
      module_function
      def param; @param end
      def param= v; @param = v end
    end
    
    SomeModule.param
    # => nil
    SomeModule.param = 1
    SomeModule.param
    # => 1
    

    The instance variable @param will then belong to the module SomeModule, which is an instance of the Module class.

提交回复
热议问题