Ruby Constants

Constants store values that cannot be changed during execution.

For example:

PI = 3.14
puts PI # 3.14

# Now try and reassign PI
PI = 30
# (irb):2: warning: already initialized constant PI
# (irb):1: warning: previous definition of PI was here

In this example, `PI` is a constant representing the value of Pi. Once assigned, the value of `PI` remains the same throughout the execution of the program. This leads to code clarity and prevents an inadvertent alteration of the value of PI in another part of the code.

This prevents pi from being overwritten from 3.14 to 3.14159265358979323846264338327950288419716939937510 when your code doesn’t really call for that level of precision.

Constants are meant to hold values that will not change and are also meant to increase clarity of code so they are often declared inside a class or module.

class SomeMathStuff
  PI = 3.14
  EULERS_NUMBER = 2.718281828459045
  GOLDEN_RATIO = 1.618033988749895
  C = 299_792 # The speed of light in a vacuum in kilometers per second

  def self.area_of_a_circle(radius)
    PI * radius * radius
  end
end

SomeMathStuff::PI # 3.14
SomeMathStuff::EULERS_NUMBER # 2.718281828459045
SomeMathStuff::GOLDEN_RATIO # 1.618033988749895
SomeMathStuff::C # 299792
SomeMathStuff.area_of_a_circle(3) # 28.259999999999998

As you can see above, you can have multiple constants in a class and the class can use the constants in it’s methods.

Some good Practices for Constants

Uppercase Naming: Name constants using all uppercase letters for improved readability is considered a Ruby standard. Constants can be named with only the first letter capitalized but it is not common to do so. Constants are written in all uppercase, in part, to visually differentiate them from classes and modules.

Avoid Naming Conflicts: Steer clear of naming constants with the same identifiers as existing classes, modules, or methods.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *