0
0
Rubyprogramming~3 mins

Why Constants in classes in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if changing one number could fix your whole program instantly?

The Scenario

Imagine you have a program where you need to use the same fixed value, like a tax rate or a maximum score, in many places. You write that number everywhere by hand.

The Problem

When you want to change that value, you have to find and update every single spot manually. This is slow and easy to miss, causing bugs and confusion.

The Solution

Using constants inside classes lets you store that fixed value in one place. You can use it everywhere by referring to the constant, so changing it once updates all uses automatically.

Before vs After
Before
tax_rate = 0.08
price_with_tax = price * (1 + 0.08)
After
class Store
  TAX_RATE = 0.08
end
price_with_tax = price * (1 + Store::TAX_RATE)
What It Enables

You can keep your fixed values organized and easy to update, making your code cleaner and safer.

Real Life Example

Think of a game where the maximum player level is a constant. Defining it once in a class constant means you can change the max level easily without hunting through all the code.

Key Takeaways

Constants store fixed values in one place.

They prevent mistakes from repeated manual changes.

Using class constants keeps code clear and easy to maintain.