Create module variables in Ruby Create module variables in Ruby ruby ruby

Create module variables in Ruby


Ruby natively supports class variables in modules, so you can use class variables directly, and not some proxy or pseudo-class-variables:

module Site  @@name = "StackOverflow"  def self.setName(value)    @@name = value  end  def self.name    @@name  endendSite.name            # => "StackOverflow"Site.setName("Test")Site.name            # => "Test"


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 endendSomeModule.param# => nilSomeModule.param = 1SomeModule.param# => 1

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


you can set a class instance variable in the module.

module MyModule   class << self; attr_accessor :var; endendMyModule.var = 'this is saved at @var'MyModule.var    => "this is saved at @var"