86

This is a simple one, I hope. How do I check, in the following example, if a constant is already defined?

#this works var = var||1 puts var var = var||2 puts var #this doesn't CONST = CONST||1 puts CONST CONST = CONST||2 puts CONST => 1 1 uninitialized constant CONST (NameError) 

3 Answers 3

145
CONST = 2 unless defined? CONST 

See here for more about awesome defined? operator.

P.S. And in the future I guess you'll want var ||= 1 instead of var = var||1.

Sign up to request clarification or add additional context in comments.

5 Comments

There's also const_defined? but it doesn't work for me; not sure why.
const_defined? is a method of Module class and it will tell you whether the constant is defined in that module and its ancestors (optionally). Check the docs for some examples — ruby-doc.org/core-1.9.3/Module.html#method-i-const_defined-3F
Thanks for this answer.. great workaround for not being able to use ||= reliably with a boolean
This works great for methods as well, not just constants.
31

const_defined? API

pry> User.const_defined?("PER_PAGE") => true pry> User.const_defined?("PER_PAGE123") => false 

1 Comment

This is especially helpful when you are checking if this is defined in a dynamic way.
4
CONST ||= :default_value 

the above works for me on ruby 1.9.3 but fails on 1.8... well 1.8 is ancient now.

2 Comments

:) 1.8 may be ancient, but still in use in 2017, example: Dreamhost shared hosting.
I see most projects have already dropped support for ruby 1.8. I know that there are still "supported" ruby 1.8 versions, e.g. shipped by Red Hat Enterprise Linux. They are getting security patches but one exposes to many unknown security flaws in old gem versions used in whatever application is installed. So yes, there is, but is irrelevant for most people. Like there are and will be for a long time computers running XP (just recently spotted again such an ATM).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.