From: Brian Candler Date: 2009-10-13T17:52:56+09:00 Subject: Re: Scope of constants in instance_eval pharrington wrote: > well in Ruby 1.8 something like this works (obviously not it all > cases, but you get the gist and can fix it as needed): > > Obj.new { puts "CONST = #{self.class.const_get("CONST")}" } Or more simply, self.class::CONST I find this particularly useful when I wish to override a constant in a subclass, e.g. class Foo TIMEOUT = 10 def run puts "Timeout is #{self.class::TIMEOUT}" end end class Bar < Foo TIMEOUT = 20 end Bar.new.run Note that you need this trick even in ruby 1.9.2. Without it, the constant is still resolved statically, depending on in which class the method was defined: $ irb19 --simple-prompt >> RUBY_VERSION => "1.9.2" >> RUBY_DESCRIPTION => "ruby 1.9.2dev (2009-07-18 trunk 24186) [i686-linux]" >> class Foo >> TIMEOUT = 10 >> def run >> puts "Timeout is #{TIMEOUT}" >> end >> end => nil >> class Bar < Foo >> TIMEOUT = 20 >> end => 20 >> Bar.new.run Timeout is 10 => nil >> class Bar >> def run2 >> puts "Timeout is #{TIMEOUT}" >> end >> end => nil >> Bar.new.run2 Timeout is 20 ## ruby1.8 shows 10 here => nil -- Posted via http://www.ruby-forum.com/.