Table of contents
1.
Introduction
2.
Defining a constant
3.
Constant Can Change
4.
Constant Methods
5.
Ruby Constant Scope
6.
Frequently Asked Questions
6.1.
What are Ruby variables?
6.2.
What is a global constant in Ruby?
6.3.
What is the definition of a class constant in Ruby?
6.4.
Is String Literal in Ruby Mutable?
6.5.
Why are Ruby classes constant, and why is it important?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Constant References in ruby

Author SAURABH ANAND
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this blog, we will see how a constant behaves in Ruby. So let’s get started with the introduction to constants and their relation and difference with variables. 

In Ruby, a constant is similar to a variable, except its value is expected to remain constant throughout the program. The Ruby interpreter does not enforce constant consistency, although it does send a warning if a program modifies a constant's value. Constant names are similar to the names of local variables in lexical similarity; the only difference is that they all start with a capital letter.

For example:

VALUE_OF_PI = 3.14      # Defining a Constant References in ruby.

Defining a constant

In this section, we will see how a constant is defined in ruby. So, are u excited? Let’s go.

Declaring a constant does not necessitate the use of any specific symbols or syntax. All you have to do now is change the initial letter to an uppercase letter. 

Most constants are written in full uppercase with underscores between words as a matter of convention. Class and module names in Ruby are also constants. However, they are written in camel case with starting capital letters.

Constants have the visibility of global variables, despite their appearance of local variables with capital letters: they can be used anywhere in a Ruby application, regardless of scope. Constants, unlike global variables, can be specified by classes and modules and hence have qualified names.

 

The following are valid Constant References in ruby:

AXE = 1
PI = 3.14
Planck = 6.6
You can also try this code with Online Ruby Compiler
Run Code


It's worth noting that constants can't be defined within a method.

def the_method
 AXE = 1
End
You can also try this code with Online Ruby Compiler
Run Code

 

Error: 

main.rb:3: dynamic constant assignment
  AXE = 1
       ^

Constant Can Change

Constant References in ruby can change, as we have seen in the introduction.

Example:

AXE = 1
AXE = 2
puts AXE
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

main.rb:2: warning: already initialized constant AXE
main.rb:1: warning: previous definition of AXE was here
2

 

From the example above, we saw that Ruby doesn’t stop us from changing the value of the constant. But, it throws a warning. Our program will continue to function normally, but we must avoid this.

We can create an immutable constant by using the freeze keyword.

Example:

PLAYER = "saurabh yadav".freeze
PLAYER << "o"
puts PLAYER
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

main.rb:2:in `<main>': can't modify frozen String (RuntimeError)

Constant Methods

There are a few approaches to dealing with constants:

Method

Description

const_set A constant's value is set. It requires two parameters: a constant name as a symbol and a constant value.
constants This method returns an array of symbols representing the constants defined in a class.
const_get Returns value for a constant. Takes a symbol or string as a parameter
const_missing It is the Same as method_missing but used for constants.
const_defined? If a given constant has been defined, this function returns true.
remove_const Constant is removed
private_constant It turns a constant private so it mustn't be accessed outside the class with Class::AXE syntax

These methods can be used to perform a few metaprogramming tricks.

Example:

module Snacks
  class Chips; end
  class MilkChocolate; end
end

puts "Classes defined inside #{Snacks}:"
puts Snacks.constants
You can also try this code with Online Ruby Compiler
Run Code


Output:

Classes defined inside Snacks:
Chips
MilkChocolate

Ruby Constant Scope

When we create a constant outside of any class, at the top of your code, it is available everywhere.

Constants specified outside of a nested module or class are available within the nested classes as well.

module Snacks
STORE_ADDRESS = "Milk"
class Chocolate
def foo; puts STORE_ADDRESS; end
end
end
fb = Snacks::Chocolate.new
fb.foo
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

Milk

 

Constants are also available in child classes.

class Snacks
def Lassi
"Lassi is not good"
end
end
class Chocolate < Snacks
def Lassi
"Lassi is good"
end
end
p Snacks.new.Lassi 
p Chocolate.new.Lassi
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

"Lassi is not good"
"Lassi is good"

Frequently Asked Questions

What are Ruby variables?

Variables in Ruby store data that may be utilized later in a program. Each variable serves as a memory and is given a unique name.\

There are four types of variables in Ruby:

  • Local variable
  • Class variable
  • Instance variable
  • Global variable

What is a global constant in Ruby?

The environment variable for the entire program is an example of a global constant. Let's look at some examples of Ruby constant lists: We'll look at constants defined at the top of the program and how to use them both inside and outside of it in this example.

What is the definition of a class constant in Ruby?

Class constants can be useful if you need to define some constant data within a class.

Constants of the class, the name of a constant begins with an uppercase letter. It should only be given a value once. Reassignment of a constant generates a warning but not an error in the current Ruby implementation (the non-ANSI version of eval .rb does not report the warning).

Is String Literal in Ruby Mutable?

The []= method in Ruby can be used to modify a portion of a string. To use this function, simply supply the string of characters to be replaced and assign the new string to the method.

Why are Ruby classes constant, and why is it important?

You're getting an " uninitialized constant " error because you most likely forgot to require a file or gem that defines the constant, you're getting an "uninitialized constant" error.

Conclusion

In this article, we have extensively discussed the concept of the Constant References in ruby. We started with the introduction of Constant References in ruby, uninitialized constant error, Constant method references in ruby, and scope of Constant References in ruby.

After reading about the Constant References in ruby, are you not feeling excited to read/explore more articles on the topic of ruby? Don't worry; Coding Ninjas has you covered. To learn, see  String literal in RubyConstants in Ruby, and Methods in Ruby.

 Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your capacity in coding, you may check out the mock test series and participate in the contests hosted on the Coding Ninjas Studio website. But if you have just started learning and are looking for questions asked by tech giants like Amazon, Microsoft, Google, Uber, etc., you must look at the problemsinterview experiences, and interview bundle for placement preparations.

You may also consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Conclusion Image

Live masterclass