loading...

re: A trick with Ruby array literals VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Interesting trick to create enums values on the fly, though I guess those are variables not constants, but maybe one can sneak a .freeze inline 😂
 

I guess those are variables not constants

This sentence confused me. Ruby uses the case of the LHS to determine if something is considered a constant or not (they can still be are-assigned though, but at least you'll get a warning). .freeze only freezes the RHS, so it can't be further mutated, but that doesn't really change Ruby's constant semantics.

RED = 'red'
Object.const_defined?('RED')
#=> true
local_variables
#=> [:_]
RED = 'blue'
(irb):4: warning: already initialized constant RED
(irb):1: warning: previous definition of RED was here
RED
#=> "blue"
RED << ' oh no'
#=> "blue oh no"
RED = 'red'.freeze
(irb):7: warning: already initialized constant RED
(irb):4: warning: previous definition of RED was here
RED << ' oh no'
Traceback (most recent call last):
...
FrozenError (can't modify frozen String: "red")
RED = 'green'
(irb):9: warning: already initialized constant RED
(irb):7: warning: previous definition of RED was here
RED
#=> "green"

Did I misunderstand what you meant? Or was your comment simply referring to the fact that Ruby constants aren't quite as constant when they are assigned a mutable value?

code of conduct - report abuse