title: How to redefine a Ruby constant without warning?
body: <p>I'm running some Ruby code which evals a Ruby file every time its date changes. In the file, I have constant definitions, like</p>
  
  <pre><code>Tau = 2 * Pi
  </code></pre>
  
  <p>and, of course, they make the interpreter display the unwanted "already initialized constant" warning every time, so, I'd like to have the following functions:</p>
  
  <pre><code>def_if_not_defined(:Tau, 2 * Pi)
  redef_without_warning(:Tau, 2 * Pi)
  </code></pre>
  
  <p>I could avoid the warning by writing all my constant definitions like this:</p>
  
  <pre><code>Tau = 2 * Pi unless defined?(Tau)
  </code></pre>
  
  <p>but it is inelegant and a bit wet (not <a href="http://en.wikipedia.org/wiki/DRY" rel="noreferrer">DRY</a>).</p>
  
  <p>Is there a better way to <code>def_if_not_defined</code>? And how to <code>redef_without_warning</code>?</p>
  
  <p>--</p>
  
  <p>Solution thanks to Steve:</p>
  
  <pre><code>class Object
    def def_if_not_defined(const, value)
      mod = self.is_a?(Module) ? self : self.class
      mod.const_set(const, value) unless mod.const_defined?(const)
    end
  
    def redef_without_warning(const, value)
      mod = self.is_a?(Module) ? self : self.class
      mod.send(:remove_const, const) if mod.const_defined?(const)
      mod.const_set(const, value)
    end
  end
  
  A = 1
  redef_without_warning :A, 2
  fail 'unit test' unless A == 2
  module M
    B = 10
    redef_without_warning :B, 20
  end
  fail 'unit test' unless M::B == 20
  </code></pre>
  
  <p>--</p>
  
  <p>This question is old. The above code is only necessary for Ruby 1.8. In Ruby 1.9, P3t3rU5's answer produces no warning and is simply better.</p>