Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 19 / 68

Constants (names starting with a capital)

In this lesson you will learn how constants work in Ruby - names starting with a capital letter - and the convention around values you do not rewrite. This is for anyone searching for "Ruby constants how to use".

In Ruby a variable name starting with a capital letter is automatically treated as a constant. Trying to change it produces a warning. No special sigil such as $ or @ is needed - simply capitalising it is enough, which is a pleasantly clear rule.

The sample code uses the capitalised name MAX_SCORE and prints its value through interpolation. Note the convention of writing constant names in capitals with underscores.

A common stumbling block for beginners is that a Ruby constant is really "a changeable variable that warns you". Since the change still goes through despite the warning, it works as a promise rather than a guarantee - there is no strict enforcement as in some other languages.

Combining it with freeze() creates an object that genuinely refuses to be rewritten. Wanting to pin a value down - configuration settings, API keys - comes up constantly in real projects.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)