Check if a constant is already defined

RubyConstants

Ruby Problem Overview


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)

Ruby Solutions


Solution 1 - Ruby

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.

Solution 2 - Ruby

const_defined? API

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

Solution 3 - Ruby

CONST ||= :default_value

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpeterView Question on Stackoverflow
Solution 1 - RubyjibielView Answer on Stackoverflow
Solution 2 - RubyrusllonrailsView Answer on Stackoverflow
Solution 3 - RubyakostadinovView Answer on Stackoverflow