๐ŸŽ“ A1Learner
๐Ÿ”

Ruby Constants

A constant is a name written in capital letters. A constant is meant to hold one value that stays fixed.

A constant holds a value

LIMIT is written in capital letters. The puts line prints the value stored in it.

LIMIT = 100
puts LIMIT

One value changes, one stays

The variable count changes between the prints. LIMIT prints the same value both times.

LIMIT = 10
count = 1
puts LIMIT
puts count
count = 2
puts LIMIT
puts count

Changing a constant warns

The second line stores a new value in LIMIT. Ruby prints a warning, and the program prints no value here.

LIMIT = 5
LIMIT = 9

Example

MAX_SCORE = 100
score = 80
puts MAX_SCORE
puts score
score = 90
puts score

Key points

  • A constant is a name meant to stay fixed.
  • A constant name starts with a capital letter.
  • Constant names in this course use capital letters for the whole name.
  • Use = to store a value in a constant.
  • Storing a new value in a constant prints a warning.
  • The value still changes after the warning.

In this example, MAX_SCORE holds 100. score holds 80, and the next line prints it. score then holds 90, and the last line prints 90.

Note

A warning is not an error, and the program still runs.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Ruby Compiler

Exercise

Which line stores the number 100 in a constant named LIMIT?