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.
Syntax
Always starts with $
Ex: $hello is a Global Variable.
Here is an illustration of how to use a global variable.
#!/usr/bin/ruby
$globalVariable = 25
class NewClass1
def print_global
puts "Global variable is NewClass1 is #$globalVariable"
end
end
class NewClass2
def print_global
puts "Global variable in NewClass2 is #$globalVariable"
end
end
class1obj = NewClass1.new
class1obj.print_global
class2obj = NewClass2.new
class2obj.print_global
Output:
Global variable in NewClass1 is 25,
Global variable in NewClass2 is 25
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 initialized.
- A nil value will be assigned to an uninitialized instance variable.
Syntax
It always starts with @
Ex: @hello is a instance Variable.
Here is an illustration of how to use instance variables.
#!/usr/bin/ruby
class NewCustomer
def initialize(id, name, addr)
@custId = id
@custName = name
@custAddr = addr
end
def display_details()
puts "Customer id #@custId"
puts "Customer name #@custName"
puts "Customer address #@custAddr"
end
end
# Create Objects
cust1 = NewCustomer.new("1", "Ninja1", "State Building, Delhi")
cust2 = NewCustomer.new("2", "Ninja2", "Empire Building, Noida")
# Call Methods
cust1.display_details()
cust2.display_details()
Here, @custId, @custName and @custAddr are instance variables. This will produce the following result −
OUTPUT
Customer id 1
Customer name Ninja1
Customer address State Building, Delhi
Customer id 2
Customer name Ninja2
Customer address Empire Building, Noida
Class Variables
Before they may be utilized in method declarations, class variables with the prefix @@ must first be initialized. An error results from using a class variable that has not been initialized. Class variables are shared by all class members or modules specified in. With the -w option, overriding class variables generates warnings.
Syntax
Always starts with @@
Ex: @@hello is a class Variable.
Here is an illustration of how to use a class variable:
#!/usr/bin/ruby
class Customer
@@no_of_customers = 50
def initialize(id, name, addr)
@cust_id = id
@cust_name = name
@cust_addr = addr
end
def display_details()
puts "Customer id #@cust_id"
puts "Customer name #@cust_name"
puts "Customer address #@cust_addr"
end
def total_no_of_customers()
@@no_of_customers += 1
puts "Total number of customers: #@@no_of_customers"
end
end
# Create Objects
cust1 = Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2 = Customer.new("2", "Poul", "New Empire road, Khandala")
# Call Methods
cust1.total_no_of_customers()
cust2.total_no_of_customers()
Here @@no_of_customers is a class variable. This will produce the following result −
OUTPUT
Total number of customers: 51
Total number of customers: 52
Local Variables
Local variables begin with a lowercase letter or _. The range of a local variable is from the opening brace of a block to the closing brace or from class, module, def, or do to the appropriate end.
References to uninitialized local variables are treated as calls to methods with no parameters.
Declaring a variable also involves assigning it to local variables that have not been initialized. Until the current scope is exhausted, the variables begin to exist. Ruby analyzes the program to determine the lifespan of local variables.
Syntax:
Begin with the lowercase letter of _.
age = 10
_Age = 20
Here is an illustration of the local variable:
#!/usr/bin/ruby
class Customer
@@no_of_customers = 50
def initialize(id, name, addr)
@cust_id = id
@cust_name = name
@cust_addr = addr
end
def display_details()
puts "Customer id #@cust_id"
puts "Customer name #@cust_name"
puts "Customer address #@cust_addr"
end
def total_no_of_customers()
@@no_of_customers += 1
puts "Total number of customers: #@@no_of_customers"
end
end
# Create Objects
cust1 = Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2 = Customer.new("2", "Poul", "New Empire road, Khandala")
# Call Methods
cust1.total_no_of_customers()
cust2.total_no_of_customers()
Here id, name, and addr are Local variables. This will produce the following result −
OUTPUT
Total number of customers: 51
Total number of customers: 52
Let us now discuss Constants in Ruby:
Constants in ruby
A fixed value employed in algebraic expressions and equations is known as a constant. A constant has a fixed value and does not change over time. For instance, the size of a shoe, piece of clothing, or any item will not alter.
In an algebraic expression, x+y = 8, 8 is a constant value that cannot be changed.
With an uppercase letter, constants are introduced. Constants specified outside of a class or module can be accessible globally, whereas those defined inside of a class or module can be accessed from within that class or module.
It is not allowed to define constants within methods. An error results from referencing an uninitialized constant. A warning is generated when an assignment is made to a constant that has already been initialized.
Syntax
Constants begin with an uppercase letter
Ex: Temp is a constant
Let us now see the Implementation for the same:
#!/usr/bin/ruby
class ConstantExample
TEMP1 = 10
TEMP2 = 20
def show
puts "Value of first Constant is #{TEMP1}"
puts "Value of second Constant is #{TEMP2}"
end
end
# Create Objects
object = ConstantExample.new()
object.show
Here, TEMP1 and TEMP2 are constants. This will produce the following result −
OUTPUT
Value of first Constant is 10
Value of second Constant is 20
Frequently Asked Questions
What are ruby variables?
Data that can be used later in a program is stored in ruby variables. The names of each variable, which functions as memory, vary. There are four types of variables in Ruby i.e, local variable, class variable, instance variable, and global variable.
Explain in brief about the ruby module ?
A Ruby module is a grouping of constants and methods. Module methods or instance methods can both be used in modules. Since they contain a collection of methods, class definitions, constants, and other modules, they are comparable to classes. They are described similarly to classes. Modules can not be used to construct objects or subclasses. There is no hierarchy of inheritance for modules.
What are ruby strings?
An arbitrarily ordered series of bytes that often represent characters can be stored and modified in a Ruby string object. They are produced by either using literals or String::new.
What Ruby does do when it concatenates strings. How many different ways are there to concatenate a string?
Ruby string concatenation refers to combining several strings into a single string. Concatenating strings allows you to connect multiple strings to create a single string. Ruby strings can be combined in one string using four different methods. They use a plus sign, a single space, a << symbol, and the concat method.
In Ruby, how to make a new time instance?
With::new, a fresh instance of Time can be produced. This will consume time from your present system. Time can also be divided into a year, month, day, hour, minute, etc.
You must wait at least a year before starting a new time instance. If only a year has passed, the system will set the time to 00:00:00 on January 1 of that year using the current time zone.
Conclusion
In this article, we discussed the variable and constants in ruby and will also understand the different types of variables in ruby along with examples. You can refer to these links for more information
- Ruby
-
Ruby
- Documentation
- Official Ruby FAQ
- Ruby Koans
Please refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. And also, enroll in our courses and refer to the mock test and problems available. Have a look at the interview experiences and interview bundle for placement preparations.
Please upvote our blog to help other ninjas grow.
Happy Learning!