What is the right way to initialize a constant in Ruby?
Posted
by
zbrimhall
on Stack Overflow
See other posts from Stack Overflow
or by zbrimhall
Published on 2010-12-26T01:26:03Z
Indexed on
2010/12/26
1:54 UTC
Read the original article
Hit count: 524
ruby
|class-design
I have a simple class that defines some constants, e.g.:
module Foo
class Bar
BAZ = "bof"
...
Everything is puppies and rainbows until I tell Rake to run all my Test::Unit
tests. When it does, I get warnings:
bar.rb:3: warning: already initialized constant BAZ
My habit has been to avoid these warnings by making the constant initialization conditional, e.g.:
...
BAZ = "bof" unless const_defined? :BAZ
...
This seems to solve the problem, but it is a little tedious, and I don't ever see anyone else initializing constants this way. This makes me think I might be Doing It Wrong. Is there a better way to initialize constants that won't generate warnings?
© Stack Overflow or respective owner