ruby - 动态常量赋值

标签 ruby

class MyClass
  def mymethod
    MYCONSTANT = "blah"
  end
end

给我错误:

SyntaxError: dynamic constant assignment error

为什么这被认为是一个动态常数?我只是为其分配一个字符串。

最佳答案

您的问题是,每次运行该方法时,您都会为常量分配一个新值。这是不允许的,因为它使常量变得非常量;即使字符串的内容 是相同的(至少就目前而言),实际的字符串对象 本身在每次调用该方法时都是不同的。例如:

def foo
  p "bar".object_id
end

foo #=> 15779172
foo #=> 15779112

也许如果您解释了您的用例——为什么要更改方法中常量的值——我们可以帮助您更好地实现。

也许您更愿意在类上有一个实例变量?

class MyClass
  class << self
    attr_accessor :my_constant
  end
  def my_method
    self.class.my_constant = "blah"
  end
end

p MyClass.my_constant #=> nil
MyClass.new.my_method

p MyClass.my_constant #=> "blah"

如果您真的想要更改方法中常量的值,而您的常量是字符串或数组,您可以“作弊”并使用#replace 方法使对象在不实际更改对象的情况下采用新值:

class MyClass
  BAR = "blah"

  def cheat(new_bar)
    BAR.replace new_bar
  end
end

p MyClass::BAR           #=> "blah"
MyClass.new.cheat "whee"
p MyClass::BAR           #=> "whee"

关于ruby - 动态常量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6712298/

相关文章:

ruby - 如何计算自 Ruby 中给定日期以来的周数?

ruby - 如何在使用门卫的 oauth 提供商上为我的用户预授权客户端应用程序?

ruby - 两种舍入方法给出不同的结果

ruby - 如何避免 "cannot load such file -- utils/popen"来自 OSX 上的 Homebrew 软件

ruby - Rails 记录器格式化 - 插入方法名称调用记录器方法

vim 中的 Ruby 支持

ruby-on-rails - 确定字符串是否为有效的浮点值

ruby-on-rails - 每当 cron 中的 gem 命令不起作用时

ruby-on-rails - belongs_to touch : true not fired on association. 构建和嵌套属性赋值

ruby - 难以在 Windows 上安装 RSpec