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

查看:25
本文介绍了在 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天全站免登陆