Create module variables in Ruby

RubyModuleClass Variables

Ruby Problem Overview


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 initializing an instance of the module, but it can be changed (unlike constants in modules).

Ruby Solutions


Solution 1 - 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
  end
end

Site.name            # => "StackOverflow"
Site.setName("Test")
Site.name            # => "Test"

Solution 2 - Ruby

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.

Solution 3 - Ruby

you can set a class instance variable in the module.

module MyModule
   class << self; attr_accessor :var; end
end

MyModule.var = 'this is saved at @var'

MyModule.var    
=> "this is saved at @var"

Solution 4 - Ruby

You can also initialize value within module definition:

module MyModule
  class << self
    attr_accessor :my_variable
  end
  self.my_variable = 2 + 2
end

p MyModule.my_variable

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMark SzymanskiView Question on Stackoverflow
Solution 1 - RubycoreywardView Answer on Stackoverflow
Solution 2 - RubysawaView Answer on Stackoverflow
Solution 3 - RubyOrlandoView Answer on Stackoverflow
Solution 4 - RubyNakilonView Answer on Stackoverflow