What if changing one number could fix your whole program instantly?
Why Constants in classes in Ruby? - Purpose & Use Cases
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.
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.
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.
tax_rate = 0.08 price_with_tax = price * (1 + 0.08)
class Store TAX_RATE = 0.08 end price_with_tax = price * (1 + Store::TAX_RATE)
You can keep your fixed values organized and easy to update, making your code cleaner and safer.
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.
Constants store fixed values in one place.
They prevent mistakes from repeated manual changes.
Using class constants keeps code clear and easy to maintain.