Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Variables in Ruby 
2.1.
Creating Variables 
2.2.
How to use Variables?
2.3.
How Ruby does it?
2.4.
Ruby Variable Types 
2.4.1.
Local Variables 
2.4.2.
Instance Variables 
2.4.3.
Class Variables 
2.4.4.
Global Variables 
3.
Frequently Asked Questions
3.1.
What are the differences between the types of Variables in Ruby?
3.2.
What is the difference between Class Variables and Instance Variables?
3.3.
An uninitialized class variable will result in an error. Which error will be raised? 
3.4.
Why we should not use Global variables in practice? 
4.
Conclusion
Last Updated: Mar 27, 2024

Variables in Ruby

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

Introduction

Programming is the act of making something new. When you run a program, it creates a miniature universe. Things come to life and interact with one another according to the rules you establish as a creator. 

Ruby is an object-oriented programming language, like C++, Java, Javascript, and many other popular programming languages. 

Well, What’s for today? 

In this article, we are going to discuss the Variables in Ruby in detail.  

We want to give names to the "things" (objects) that our program deals with.

Variables are a feature found in every practical programming language. There are various kinds of variables in Ruby (you will learn about the different types in a bit).

Don't worry if some of this seems a little hazy to you. 

Variables in Ruby 

Ruby variables are storage locations for data that will be used in programs. Each variable has a unique name. These variable names follow naming conventions. 

Unlike other programming languages, Ruby does not require variable declaration. To indicate it, a prefix is required.

In short, a variable is just a label. It's a method of naming things in your Ruby programs.

Just like the names we give to real-world objects. 

When I say “Mango”, you know what I’m talking about. I don’t have to describe it to you. That’s what variables do!

And they're far more useful than you might imagine.

Creating Variables 

Variables are created by associating a Ruby object with a variable name.  This is known as "variable assignment."

For example

name = "Ninja"

 

When you type name, Ruby will automatically convert it into “Ninja”. Variables are just names for things. 

How to use Variables?

To use a variable, you write its name. 

puts name + "Coder"
# NinjaCoder

 

In the above example, the name is concatenated with Coder

We can also combine multiple variables together. 

firstName = "John"
lastName = "Deo"
puts firstName + lastName
#JohnDeo

 

We can also store the result of the above-concatenated string into another variable. 

firstName = "John"
lastName = "Deo"
fullName = firstName + lastName
puts fullName
#JohnDeo

 

How Ruby does it?

So, before doing anything else, Ruby will examine the right expression and evaluate it. She will then evaluate the assignment operator =).

Ruby Variable Types 

In ruby, we have different variable types. 

So far, we have used the Local Variables. Now, let us discuss each type one by one: 

Local Variables 

The name of a local variable begins with a lowercase letter or an underscore ( _ ). It is only accessible or has its scope within the initialization block. Variable has no scope once the code block is finished.

When uninitialized local variables are called, they are interpreted as a call to an empty method.

 

Example for Local Variables

_age = 32
name = “Joey”

 

Instance Variables 

The name of an instance variable begins with a @ sign. It belongs to one instance of the class and can be accessed within a method from any instance of the class. 

  • They only have restricted access to a single instance of a class.
  • They are not required to be initialised. 
  • A nil value will be assigned to an uninitialized instance variable.
     

Example for Instance Variables

# Ruby program to illustrate
# the Instance Variables

class Student
      
 def initialize(id, name)
       
# Instance Variables     
 @stu_id = id
 @stu_name = name
 end
   
 # displaying result
 def display_details()
 puts "Student id #@stu_id"
 puts "Student name #@stu_name"
 end
end
  
# Create Objects
stu1 = Student.new("1", "Joey")
stu2 = Student.new("2", "Rachel")
  
# Call Methods
stu1.display_details()
stu2.display_details()

 

Output

Class Variables 

The @@ sign precedes the name of a class variable. They must be initialised before being used. A class variable is shared by the entire class and can be accessed from anywhere within the class. If the value is changed at one instance, it is changed at all instances.

 

Example for Class Variables

# Ruby program to illustrate
# the Class Variables

class Student

# class variable
@@no_of_students = 0
def initialize(id, name)

# An instance Variable
@stu_id = id
@stu_name = name
end

def total_no_of_students()

# class variable
@@no_of_students += 1
puts "Total number of Students: #@@no_of_students"
end
end

# Create Objects
stu1 = Student.new("1", "Joey")
stu2 = Student.new("2", "Rachel")

# Call Methods
stu1.total_no_of_students()
stu2.total_no_of_students()

 

Output

Global Variables 

The name of a global variable begins with a $ sign. It has a global scope, which means it can be accessed from anywhere in a program.

Uninitialized global variables have no value. It is not recommended to use them because they make programs cryptic and complex.

 

Example for Global Variables 

# Ruby program to illustrate
# the Global Variables

$global_variable = 20
class ClassA
 def print_global
 puts "Global variable in ClassA is => #$global_variable"
 end
end
class ClassB
 def print_global
 puts "Global variable in ClassB is => #$global_variable"
 end
end
objA = ClassA.new
objA.print_global
objB = ClassB.new
objB.print_global

Output

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

Frequently Asked Questions

What are the differences between the types of Variables in Ruby?

Variables in Ruby have differences based on the scope, initialization, and Naming. The below-mentioned difference is based on Scope. 

Local : Restricted to the initialization block.

Global: It has a global scope

Instance: It is associated with a single instance of a class. 

Class: They are restricted to the entire class in which they are created.

What is the difference between Class Variables and Instance Variables?

A class variable is shared by all the descendants of the class whereas the Instance variable’s values are local to specific instances of an object. 

An uninitialized class variable will result in an error. Which error will be raised? 

NameError will be raised by the Compiler. 

Why we should not use Global variables in practice? 

Global variables are accessible throughout the program which makes it less secure as compare to other variables. As your projects grow in size, having all of your data in the global namespace becomes unsustainable.

Conclusion

In this article, we have extensively discussed Variables in Ruby, its types, examples, code basis, and faqs. We hope this blog has helped you enhance your knowledge regarding Variables in Ruby.

If you want to learn more, check out our articles on Ruby Programming LanguageRuby-DocumentationOfficial Ruby FAQ, and Learn Ruby.

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 Coding!

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