Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create module variables in Ruby

People also ask

CAN modules have variables?

If you do not need to call it from within an instance, you can simply use an instance variable within the module body. The instance variable @param will then belong to the module SomeModule , which is an instance of the Module class. Show activity on this post. you can set a class instance variable in the module.

How do you create a module in Ruby?

Creating Modules in Ruby To define a module, use the module keyword, give it a name and then finish with an end . The module name follows the same rules as class names. The name is a constant and should start with a capital letter. If the module is two words it should be camel case (e.g MyModule).

CAN modules have instance variables Ruby?

Explanation: Yes, Module instance variables are present in the class when you would include them inside the class.

What does @@ all mean in Ruby?

@@ denotes a class variable, i.e. it can be inherited. This means that if you create a subclass of that class, it will inherit the variable. So if you have a class Vehicle with the class variable @@number_of_wheels then if you create a class Car < Vehicle then it too will have the class variable @@number_of_wheels.


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"

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.


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"

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