Dynamic constant assignment

后端 未结 7 800
眼角桃花
眼角桃花 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:43

    In Ruby, any variable whose name starts with a capital letter is a constant and you can only assign to it once. Choose one of these alternatives:

    class MyClass
      MYCONSTANT = "blah"
    
      def mymethod
        MYCONSTANT
      end
    end
    
    class MyClass
      def mymethod
        my_constant = "blah"
      end
    end
    

提交回复
热议问题