动态常量赋值 [英] Dynamic constant assignment
问题描述
class MyClass
def mymethod
MYCONSTANT = "blah"
end
end
给我错误:
SyntaxError:动态常量赋值错误
SyntaxError: dynamic constant assignment error
为什么这被认为是一个动态常数?我只是给它分配一个字符串.
Why is this considered a dynamic constant? I'm just assigning a string to it.
推荐答案
您的问题是每次运行该方法时,您都会为常量分配一个新值.这是不允许的,因为它使常量非常量;即使字符串的内容是相同的(无论如何),每次调用该方法时,实际的字符串object本身都是不同的.例如:
Your problem is that each time you run the method you are assigning a new value to the constant. This is not allowed, as it makes the constant non-constant; even though the contents of the string are the same (for the moment, anyhow), the actual string object itself is different each time the method is called. For example:
def foo
p "bar".object_id
end
foo #=> 15779172
foo #=> 15779112
也许如果您解释了您的用例——为什么要更改方法中常量的值——我们可以帮助您更好地实现.
Perhaps if you explained your use case—why you want to change the value of a constant in a method—we could help you with a better implementation.
也许你更愿意在类上有一个实例变量?
Perhaps you'd rather have an instance variable on the class?
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
方法使对象采用新值而不实际更改对象:
If you really want to change the value of a constant in a method, and your constant is a String or an Array, you can 'cheat' and use the #replace
method to cause the object to take on a new value without actually changing the object:
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"
这篇关于动态常量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!