Wednesday, May 7, 2008

Ruby Constants Aren't

I don't know how I missed this but I did. This morning it bit us, hard.

Ruby constants aren't constant. Well, actually, the constant is a reference to an object. That's immutable, but you can use it to change the object it will refer to. Really. It's a feature:

"Ruby, unlike less flexible languages, lets you alter the value of a constant, although this will generate a warning message." - from Programming Ruby, by Dave Thomas

Umm, isn't that what's usually meant by "variable?" So you mean that...


irb(main):001:0> CONST = "foo"
=> "foo"
irb(main):002:0> CONST = "bar"
(irb):2: warning: already initialized constant CONST
=> "bar"


Yeah. Well, I vote we get rid of that annoying error message. It kinda spoils the thrill.