Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a constant is already defined

Tags:

ruby

constants

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) 
like image 977
peter Avatar asked Apr 16 '12 09:04

peter


People also ask

How do you check if a constant is defined in PHP?

Checking if a PHP Constant is Defined This can be achieved using the PHP defined() function. The defined() function takes the name of the constant to be checked as an argument and returns a value of true or false to indicate whether that constant exists.

What is define () in PHP?

Definition and Usage The define() function defines a constant. Constants are much like variables, except for the following differences: A constant's value cannot be changed after it is set. Constant names do not need a leading dollar sign ($) Constants can be accessed regardless of scope.

Can you redefine a constant?

No, you cannot redefine a constant (except with runkit_constant_redefine), that's why is called CONSTANT.

What is difference between constant and define in PHP?

The basic difference between these two is that const defines constants at compile time, whereas define() defines them at run time. We can't use the const keyword to declare constant in conditional blocks, while with define() we can achieve that.


2 Answers

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.

like image 123
jibiel Avatar answered Sep 23 '22 03:09

jibiel


const_defined? API

pry> User.const_defined?("PER_PAGE") => true pry> User.const_defined?("PER_PAGE123") => false 
like image 21
rusllonrails Avatar answered Sep 21 '22 03:09

rusllonrails