How to declare a constant in Ruby?

Asked

Viewed 845 times

7

How to declare a constant in Ruby? In other languages I do something like:

const CONSTANTE = 1024

And CONSTANTE cannot be changed at runtime. But I can’t find anything like this in Ruby.

3 answers

9

One of the things I like about Ruby is the adoption of philosophy Convention over Configuration. This means that there is a way that you use something and 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 has to do:

Constante = 1

I put in the Github for future reference.

You may be thinking, but what does this differ from the variable? Simple, the name is beginning with uppercase, this already says that it is a constant, the variables must start with lowercase.

This even has the advantage that there is no implicit default statement. You are always being explicit without creating noise in the text.

Note that it does not generate an error, just an alert, so you are allowed to change the value if you really want to. There is no true constant in Ruby. It’s just a statement of intent.

It’s the same thing estado and Estado. Depending on the spelling, they’re very different things.

I don’t like all the conventions Ruby’s adopted, but the general idea is pretty cool.

Some people prefer to capitalize everything, but it’s not mandatory and I don’t like it.

  • 1

    By convention the full name is used in upper case by separating the words with '_', for example: MINHA_CONSTANTE = 15.

  • 3

    @Hamurabiaraujo convention of some people, not of language, language only looks at the first character.

  • Yes, of course. Only one standard adopted by the community. Thank you for the caveat.

  • Is it a constant or variable? See spinning.

  • @vnbrs I edited to put it.

3


Ruby doesn’t have constants "really".

Like @Maniero said in his reply, it is possible to use the convention to write the variable name with the first uppercase letter. This will cause the interpreter to generate a Warning, saying that the value contained therein should not be reallocated.

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, one needs to look carefully before making this kind of decision.

An example of what I said is to do:

def constante()
    return 1024
end

puts constante()

See working on Repl.it | Rubyfiddle

  • I believe I am the only workaround for a truth constant in that language.

  • @vnbrs Honestly, so do I. There are cases where risking is to give room for mistakes that cannot happen.

-1

  • 1

    The Object#freeze is interesting, but does not make a constant. It hangs the object instance. For example: "constante".freeze.upcase! generates a FrozenError.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.