I am working on a Rails application where in one class, constants are defined using const_set constant_name, value
.
I know we can define constants directly in class by just specifying the CAPITALIZE name of the constant with its value like following
class A
RANDOM_CONSTANT = 1
end
so what is the difference between defining constants using const_set
and simply the way I have declared in class A
?
is simpler to write and read. This should be the preferred way to set a constant.
will work when the constant name is dynamically generated, and thus more flexible. You'd typically use it only when you want to do some metaprogramming magic.
Other than that, they are equivalent.