From: "David A. Black" Date: 2004-08-07T23:12:44+09:00 Subject: Re: const_defined? raises NameError ? Hi -- On Sat, 7 Aug 2004, [ISO-8859-2] Marcin Miel�y�ski wrote: > Hi, > > Given a const how can I check whether the const exists > without rescuing an exception thrown - if it isn't? > (using const_set is not elegant since You have to supply a special value) > > if const_defined?('SomeConst') > ... > end if defined?(SomeConst) > My next qusetion is: > Assuming there is a nested const: > > module SomeModule > Const="somevalue" > end > > the only way to access it by reflection is: > > s='SomeModule::Const' > mod,con=s.split(/::/).map{|e|e.strip} > Object.const_get(mod).const_get(con) > > wouldn't it be easier if the following worked avoiding any eval calls: > > object.const_get('SomeModule::Const') I've seen code floating around that does that. It's not too hard to implement (definitely no eval needed): def const_get_deep(str) str.split("::").inject(Object) {|x,y| x = x.const_get(y)} end class A class B C = 1 end end p const_get_deep("A::B::C") # 1 I guess it might be useful to have this in the core. I don't know whether it's been considered by Matz in the past. David -- David A. Black dblack@wobblini.net