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/