Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction to Ruby
2.
Constants in Ruby
3.
Ruby Classes as Constants
4.
How to Define Constants
5.
How to Change Constants
6.
Constant Method
7.
Frequently Asked Questions
7.1.
In Ruby, how do you write constants?
7.2.
What is a global constant in Ruby?
7.3.
What is the definition of a class constant in Ruby?
7.4.
Why are Ruby classes constant, and why is it important?
8.
Conclusion
Last Updated: Mar 27, 2024

Constants in Ruby

Author Kanak Rana
1 upvote
gp-icon
Data structures & algorithms (Beginner to Intermediate)
Free guided path
13 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction to Ruby

Ruby is an object-oriented programming language that is general-purpose, dynamic, and reflective. Except for blocks, which have replacements in the form of procs and lambda, everything in Ruby is an object. The goal of Ruby's development it was to create a user interface between human programmers and the computational machinery that underpins them.

Ruby's syntax is similar to that of many other programming languages, including C and Java, making learning easy for Java and C programmers. It runs on various operating systems, including Windows, Mac OS X, and Linux.

Let's talk about what are constants in ruby and how to do it in Ruby.

Constants in Ruby

An uppercase letter is used to start a constant. Constants defined within a class or module can be accessed only from within that class or module, while those defined outside of it can be accessed globally.

For example-

VAR1 = "hello world"
 

#Output

=> "hello world"

It is not possible to define constants within methods. When you refer to an uninitialized constant, you get an error. You get a warning when you assign to a constant that has already been initialized.

For example-

VAR1 = "hello, Coding Ninjas."

#Output

(irb):34: warning: already initialized constant VAR1

=> "hello, Coding Ninjas."

  • Unless you use metaprogramming, Constants can only be defined outside of methods.
  • Constants are used for values that should not change, but Ruby allows you to change them.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Ruby Classes as Constants

Since the first letter is uppercase, the variables are constants. When you define a class, you create a Class object and assign it to a constant. The constant takes on the role of the class name.

For example: String, Hash, Array

How to Define Constants

  • Declaring a constant does not necessitate using any special symbols or syntax. Now, you have to change the first letter to an uppercase letter.
     
ANIMAL = " Lion"
puts ANIMAL
Bird = “Sparrow”


Output:

Lion

Sparrow

Explanation - Both ANIMAL and Bird are constants.

  • Dynamic Constant Assignment
     
def the_method
  VAR = 1
end


Output:

main.rb:11: dynamic constant assignment

  VAR = 1

How to Change Constants

Constants in ruby can change.  Variables in Ruby are not containers but pointers to objects, there is no way to prevent a constant from changing. If you prefer, you can use labels. Here we can use immutable objects.

For example:

VAR1 = 1
VAR1 = 2
puts VAR1


Output:

main.rb:9: warning: already initialized constant VAR1

main.rb:8: warning: previous definition of VAR1 was here

2

Explanation- Your program will continue to function normally, but you must avoid the errors coming in the program.

Constant Method

A few methods are working with constants:

constants Return a symbol array that represents the constants defined class
const_get

Takes symbol string as a parameter and return value for constant in ruby 

 

const_defined? If the given constant is defined, it returns true
const_set Takes two parameters, one is a constant value, the second is a constant name(symbol), and set the value for a constant.
remove_const Used to remove a constant
private_constant Class::VAR syntax makes a constant private, so it can't be accessed outside the class.

 

Frequently Asked Questions

In Ruby, how do you write constants?

A capital letter is used to start a constant. Constants defined within a class or module can be accessed only from within that class or module, while those defined outside of it can be accessed globally. It is not possible to define constants within methods.

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).

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

This blog covered the details on Constants in Ruby. We learned how to define constants,  learned that constants can change, and also looked at a constant method example.

If you want to learn more, check out our articles/blogs on ruby and refer to Ruby Documentation for more information. You can also learn more about ruby from:

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow. 

Happy Learning Ninja! 🥷

Previous article
Boolean in Ruby
Next article
Variables in Ruby
Guided path
Free
gridgp-icon
Data structures & algorithms (Beginner to Intermediate)
13 chapters
109+ Problems
gp-badge
Earn badges and level up
Live masterclass