83

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)
Brad Werth
  • 16,308
  • 9
  • 57
  • 85
peter
  • 40,314
  • 5
  • 58
  • 99

3 Answers3

138
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.

jibiel
  • 7,195
  • 7
  • 46
  • 64
  • 6
    There's also `const_defined?` but it doesn't work for me; not sure why. – Jared Beck Jun 05 '13 at 22:46
  • 8
    `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 — http://www.ruby-doc.org/core-1.9.3/Module.html#method-i-const_defined-3F – jibiel Jun 08 '13 at 21:01
  • And what about this? http://ruby-doc.org/core-1.9.3/Module.html#method-i-const_defined-3F – Donato Mar 03 '15 at 00:09
  • Thanks for this answer.. great workaround for not being able to use ||= reliably with a boolean – Chuck van der Linden Apr 16 '15 at 22:35
  • This works great for methods as well, not just constants. – Joshua Pinter Mar 11 '18 at 17:08
26

const_defined? API

pry> User.const_defined?("PER_PAGE")
=> true
pry> User.const_defined?("PER_PAGE123")
=> false
Xavi
  • 19,255
  • 13
  • 68
  • 63
rusllonrails
  • 4,850
  • 1
  • 31
  • 27
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.

akostadinov
  • 15,093
  • 5
  • 64
  • 79
  • :) 1.8 may be ancient, but still in use in 2017, example: Dreamhost shared hosting. – manitu Jan 30 '17 at 16:00
  • 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). – akostadinov Jan 31 '17 at 09:31