Const_defined? raises NameError?

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

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')

TIA

Marcin Mielzynski

Hi --

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

···

On Sat, 7 Aug 2004, [ISO-8859-2] Marcin Miel¿yñski wrote:

--
David A. Black
dblack@wobblini.net

Hi,

>
> if defined?(SomeConst)
>

Thanks for Your answer, but I think the first question is still open
since the Const is given as a String and the const_defined?
raises an error.
Of course a can catch it but on the other hand I don't know how exception mechanisms in Ruby affect performance.

Marcin Milezynski

Thanks for Your answer, but I think the first question is still open
since the Const is given as a String and the const_defined?
raises an error.

const_defined? is a method of Module, not Kernel

svg% ruby -e 'p Object.const_defined?("Array")'
true
svg%

svg% ruby -e 'p Object.const_defined?("Arr")'
false
svg%

Guy Decoux

Dnia 2004-08-07 16:41, U¿ytkownik ts napisa³:

const_defined? is a method of Module, not Kernel

Ups, that's wright :slight_smile:

Marcin Mielzynski