在Ruby中创建模块变量 [英] Create module variables in Ruby

查看:71
本文介绍了在Ruby中创建模块变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在Ruby中的模块中创建类似于类变量的变量?我的意思是,无需初始化模块实例就可以对其进行访问,但是可以对其进行更改(与模块中的常量不同).

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原生支持模块中的类变量,因此您可以直接使用类变量,而不必使用某些代理或伪类变量:

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"

这篇关于在Ruby中创建模块变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆