Skip to main content

Benjamin Oakes

Photo of Ben Oakes

Hi, I'm Ben Oakes and this is my geek blog. Currently, I'm a Software Developer at Hedgeye. Previously, I was a Research Assistant in the Early Social Cognition Lab at Yale University and a student at the University of Iowa. I also organize NewHaven.rb. I do development with Ruby, JavaScript, SQL, HTML, and CSS. I have an amazing fiancée named Danielle Smith.

Throw exception when re-assigning a constant in Ruby?

by Ben

This has bothered me for a while, so I made a question on StackOverflow:

I’ve long been aware that “constants” in Ruby (i.e., variable names that are capitalized) aren’t really constant. Like other programming languages, a reference to an object is the only thing stored in the variable/constant. (Sidebar: Ruby does have the facility to “freeze” referenced objects from being modified, which as far as I know, isn’t an ability offered in many other languages.)

So here’s my question: when you re-assign a value into a constant, you get a warning like so:

>> FOO = 'bar'
=> "bar"
>> FOO = 'baz'
(irb):2: warning: already initialized constant FOO
=> "baz"

Is there a way to force Ruby to throw an exception instead of printing a warning?