Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

ruby - Check if a constant is already defined

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...