5

It's possible to write this way

class Foo
 MY_CONST = 100
end

and it's also possible to change it Foo::MY_CONST = 123

There will be a warning from a Ruby compiler, but anyway a constant will be changed.

So Ruby has no constant values?

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
  • 3
    Indirectly related - http://stackoverflow.com/questions/2441524/closest-ruby-representation-of-a-private-static-final-and-public-static-final#2442640 – dfb Aug 29 '12 at 15:44
  • Also related: http://stackoverflow.com/q/1977780/38765 – Andrew Grimm Aug 29 '12 at 23:14

3 Answers3

2

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

If you have an

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

Ruby won't 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
three
  • 8,262
  • 3
  • 35
  • 39
1

If you freeze FOO, then trying to reassign FOO::MY_CONST will create a RuntimeError.

class FOO
  MY_CONST = 100
end

FOO.freeze
FOO::MY_CONST = 123

gives

RuntimeError: can't modify frozen Class
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
0

They are semantically constants, so you can expect people not to change them. I'd call them liberal constants, see http://pastie.org/4608297

Reactormonk
  • 21,472
  • 14
  • 74
  • 123
  • 2
    They can be changed. Even if people might not want to change them. –  Aug 29 '12 at 16:18