Dynamic constant assignment

后端 未结 7 817
眼角桃花
眼角桃花 2020-11-28 20:31
class MyClass
  def mymethod
    MYCONSTANT = \"blah\"
  end
end

gives me the error:

SyntaxError: dynamic constant assignmen

7条回答
  •  感动是毒
    2020-11-28 20:41

    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"
    

    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"
    

提交回复
热议问题