Ruby constants are constants unless they're global
Mike Gnozzio (Williams class of '07 I think?) is working with us this
summer. We've got him writing some Ruby data analysis code. Today he
asked how you would make a global constant in Ruby.
For the unfamiliar, Ruby uses textual analysis to determine things
like constancy or globalhood. A variable whose name starts with a
capital letter is automatically constant. A variable whose name starts
with a $ is automatically global. So what about constant globals?
FOO = 1 => 1 FOO = 2 warning: already initialized constant FOO => 2 $FOO = 1 => 1 $FOO = 2 => 2Unfortunately, it can't be done. As you see above, the variable with the $ prefix is not constant. This also effects instance variables. @FOO would not be constant either. This situation is discussed here on Ruby talk. Obviously the cause is that $ and @ are considered to be the first character of the variable names, and so the name is not capitalized. This is certainly consistent and logical but it's not very useful. Ruby Talk seemed to have an attitude of "sorry, that's the way it is." I hope this changes someday though. I doesn't seem like it would cost much to do it right. Also, check out Jeremy's post about passing around Ruby methods as closures and Ben Matasar's post about turning on Emacs Snippets for Ruby development
posted on: 06/16/2006 | path: /tech