From: "Iñaki Baz Castillo" Date: 2011-05-01T08:48:43+09:00 Subject: Re: Why defining a constant in a method is not allowed but using self.class.const_set is allowed? 2011/5/1 Christopher Dicely : > It is possible. As you note, it produces a warning, because more than > one assignment to a constant indicates something that is likely to be > an error (since the use of a constant rather than a variable implies > that the value is intended to be constant once defined.) Yes, I understand that redeining a constant is not "good" in any language, just wondering why Ruby, being so flexible, also behaves like others. > At any rate, sure, constant (or global variable) lookup is maybe twice > as fast as accessing an instance variable of another object (class or > otherwise) through a simple getter method Yes, I assume it occurs because Ruby must perform two lookups: 1) the method 2) the attribute returned by the method > but are you really spending so much of your programs time on > that kind of access where speeding that access up is going to make a > difference? Well, is just minimum of course, I just wanted to study it. or sure accessing an attribute (through a method) will not be the bottleneck of my application :) > Since looking up instance variables that are in scope is about as fast > as looking up remote constants, you may (depending on the access > pattern and frequency of change involved) be able to get a similar > speedup without abusing constants simply by caching the value of the > remote attribute in a local instance variable of the objects consuming > it, and registering them as listeners that are notified on updates to > the value. It seems not very suitable in my application. Basically I get a conf file and want to store configuration data in constants (for faster lockup). But I also need to change those values in realtime. But as said before, I'll probasbly move to attribute variables. > OTOH, if you absolutely must redefine constants and avoid producing > warnings (without actually changing the settings affecting warning > levels), its simple enough to do (Ruby rarely stops you from doing > things): > > class C >  KONST = 123 >  def self.konst=(val) >    remove_const :KONST >    const_set :KONST, val >  end > end Interesting, thanks a lot :) -- Iñaki Baz Castillo