Ruby has no constant values?

Can write this way

class Foo
 MY_CONST = 100
end

and it can also be changed Foo::MY_CONST = 123

A warning from the Ruby compiler will appear, but the constant will change in any case.

So, does Ruby have no constant values?

+5
source share
3 answers

it depends on what action you want to do with your constants.

if you have

ARRAY = [1,2,3]
#and then 
ARRAY << 4

Ruby will not complain.

However, if you

ARRAY = [1,2,3].freeze
#and
ARRAY << 4
#RuntimeError: can't modify frozen Array

You can still

ARRAY = [1,2,3,4]
#warning: already initialized constant ARRAY
+3
source

If you are freeze FOO, an attempt to reassign FOO::MY_CONSTwill create a RuntimeError.

class FOO
  MY_CONST = 100
end

FOO.freeze
FOO::MY_CONST = 123

gives

RuntimeError: can't modify frozen Class
+2
source
0

All Articles