How to declare a constant in Ruby? In other languages I do something like:
const CONSTANTE = 1024
And CONSTANTE
can not be changed at run time. But I do not think anything like it in Ruby.
How to declare a constant in Ruby? In other languages I do something like:
const CONSTANTE = 1024
And CONSTANTE
can not be changed at run time. But I do not think anything like it in Ruby.
Ruby has no "real" constants.
As @Maniero said in his answer , you can use the convention to write the variable name with the first capital letter. This will cause the interpreter to generate a warning , saying that the value contained there should not be reassigned.
This, unfortunately, may not cover all cases. So my tip is to create a function for these special cases.
Of course this can be an exaggeration, you need to look carefully before you make this kind of decision.
An example of what I said is to do:
def constante()
return 1024
end
puts constante()
See working at Repl.it | RubyFiddle
One of the things I like about Ruby is the adoption of the convention over configuration philosophy. This means that there is a way that you use something and the language knows what to do, to the detriment of you having to say what you want. So while other languages require you to do:
const constante = 1
Ruby just needs to do:
Constante = 1
You may be thinking, but what does this differ from the variable? Simple, the name is beginning with a capital letter, this already says that it is a constant, the variables must begin with a lowercase.
This even has the advantage that there is no default declaration implied. You are always being explicit without creating noise in the text.
Note that it does not generate an error, just an alert, so you can change the value if you want to. There is no true constant in Ruby. It's just a statement of intent.
It's the same thing as estado
and Estado
depending on the spelling is quite a different thing.
I do not like all conventions that Ruby has adopted, but the general idea is pretty cool.
Some people prefer to put it all uppercase, but it's not mandatory and I do not like it.