0
0
Rubyprogramming~5 mins

Constants in classes in Ruby

Choose your learning style9 modes available
Introduction

Constants hold values that do not change. In classes, they keep important fixed information easy to find and use.

When you want to store a fixed value like a tax rate used by all objects of a class.
When you need a label or name that stays the same for every instance.
When you want to avoid repeating the same value in many places in your code.
When you want to make your code easier to read by giving a meaningful name to a fixed value.
Syntax
Ruby
class ClassName
  CONSTANT_NAME = value
end

Constants start with a capital letter.

They are written inside the class but outside any method.

Examples
This sets a constant WHEELS to 4 inside the Car class.
Ruby
class Car
  WHEELS = 4
end
PI is a constant for the value of pi inside the Circle class.
Ruby
class Circle
  PI = 3.14
end
ROLE is a constant string inside the User class.
Ruby
class User
  ROLE = 'guest'
end
Sample Program

This program defines a constant GENRE inside the Book class. The method show_genre prints the constant value.

Ruby
class Book
  GENRE = 'Fiction'

  def show_genre
    puts "Genre: #{GENRE}"
  end
end

book = Book.new
book.show_genre
OutputSuccess
Important Notes

Constants can be accessed inside the class directly by their name.

You can also access constants outside the class using ClassName::CONSTANT_NAME.

Ruby warns if you try to change a constant, but it still allows it.

Summary

Constants store fixed values inside classes.

They start with a capital letter and are written outside methods.

Use them to keep important values easy to find and use.