const_defined? raises NameError ?

  • Thread starter Marcin Miel¿yñski
  • Start date
M

Marcin Miel¿yñski

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
 
D

David A. Black

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
 
M

Marcin Miel¿yñski

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
 
T

ts

"M" == =?ISO-8859-2?Q?Marcin Miel=BFy=F1ski?= <ISO-8859-2> writes:

M> Thanks for Your answer, but I think the first question is still open
M> since the Const is given as a String and the const_defined?
M> 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top