app_env = "development"
APP_ENV = app_env # Error: undefined local variable or method 'app_env' for top-level
APP_ENV != "production"
Question: why compiler complain app_env is not defined?
if assign a variable to a const is not possible, why not complain that?
EDIT:
I found wherever you put const definition into where, even, when i try to read the value of const, then require the file which define the const, it still work.
so, i guess, APP_ENV = app_env is same as macro, will expanding early??
Case 2
class A
@@a ||= 100
end
# Error: class variable '@@a' of A is not nilable (it's Int32) so it must have an initializer
Question:
I thought this caused by @@a ||= 100 will expand to @@a = @@a || 100 , and @@a be used before initialize it. But i still consider this should work, because after done, @@a always be assign a non-nil value, right?
Case 1: Constant values must be known at compile time. Thus you can’t assign a runtime value such as variable to a constant.
Case 2: Yes, technically the compiler could swallow this error and just focus on the expected result, which will be unambiguous. But it’s an error for a reason: The developer seems to have a misconception about the life time and scope of this variable, so raising an error is useful to alert you of that.
One more question, if i really want to change previous defined class_variable if it exists, otherwise, i want assign a new value to it, how to workaround that?
By the way, unless ||= is defined differently than in Ruby, I’d assume it expands to @a || @a = 100. Though the difference doesn’t matter in this particular case.