Jun 302011

In ruby, you can find out whether a class is defined by calling:

Object.const_defined?('ClassName')

A simple demonstration of this in an irb session is:

ruby-1.8.7-p330 :020 > Object.const_defined?('String')
=> true
ruby-1.8.7-p330 :021 > Object.const_defined?('Asdf')
=> false

Recently I ran into the problem that some called to Object.const_defined? are raising a NameError instead of returning true or false.

ruby-1.8.7-p330 :022 > Object.const_defined?('asdf')
NameError: wrong constant name asdf
from (irb):22:in `const_defined?'
from (irb):22

I discovered that passing a string that is not capitalized is what causes this problem.

ruby-1.8.7-p330 :023 > Object.const_defined?('asdf'.capitalize)
=> false

This had me scratching my head for a minute. I hope it helps someone out.

One Response to “const_defined? raises NameError instead of returning false”

Comments (1)
  1. RyanonRails says:

    Hey Nate,

    Thanks for the tip. I was wondering why the heck some strings were working fine and others were bombing out with a NameError. Didn’t clue in until I came across this blog. I ended going up with the capitalize! method (so I didn’t break the capitalization on others). I was using Ruby 1.9.2

    Thanks,
    Ry

Leave a Reply

(required)

(required)