Variables in Ruby
A variable is simply a name that points to a value in Ruby. Ruby, in contrast to several other programming languages, is weakly typed, which means that variables are assigned their type without the need for explicit declaration of its scope or type. Any object that may be assigned to a variable in Ruby is referred to as an object, and variables in Ruby hold pointers to these objects instead of the actual objects.
Ruby separates variables into a number of categories according to their beginning characters, which also define their visibility and scope:
Local Variables
A local variable can only be defined inside its immediate “declaration container,” which could be a file, block, or procedure. An underscore (_) or a lowercase letter appears at the beginning. A local variable is only used within the method in which it is declared. When variables are used as block parameters, they are local to that block and have the ability to “overshadow” existing variables for a brief period of time without permanently overwriting them.
Code Examples: Simple Local Variable Declaration
# Declared in the top-level scope of the program
local_variable = "hello" # `local_variable` is a local variable
p local_variable # => "hello"
Output
"hello"
Instance Variables
The initial character of instance variables is a single at sign (@). They are only available via the instance methods of the particular object they are linked to (an “instance” of a class). When an item is formed, they are usually initialised.
Code Example:
class Person
def initialize(name, age)
# my_age is a local variable, destroyed at end of constructor
my_age = age
# @name is an instance variable, persists with the object
@name = name
end
def some_method
puts "My name is #{@name}." # @name can be used here
end
def another_method
# This would not work, as my_age was a local variable
# puts "My age is #{my_age}."
end
end
mhmd = Person.new("Mark", 23)
mhmd.some_method #=> My name is Mark.
# mhmd.another_method #=> throws an error
Output
My name is Mark.
Attr_reader (for reading), attr_writer (for writing), or attr_accessor (for both) are examples of accessor methods that are used to read or change instance variables from outside the class.
You can also read What Is Mean By Comments In Ruby With Code Examples
Class Variables
At signs (@@), class variables begin with two. Class methods can access them, and they are shared by all instances of a class. A given class variable exists in a single copy for each class. While instance variables are evaluated in reference to self (the instance), class variables are evaluated in reference to the class object itself, which is a fundamental difference.
Code Examples: This demonstrates how @@classification
is shared and can be overwritten across the inheritance hierarchy:
class Dinosaur
@@classification = "Like a Reptile, but like a bird"
def self.classification; @@classification; end # Accessor for the class variable
end
puts Dinosaur.classification # => "Like a Reptile, but like a bird"
class TRex < Dinosaur
@@classification = "Big teeth bird!" # Subclass alters the shared class variable
end
puts TRex.classification # => "Big teeth bird!"
puts Dinosaur.classification # => "Big teeth bird!" (Superclass sees the altered value)
class Triceratops < Dinosaur
# This subclass will also see "Big teeth bird!" because @@classification was modified by TRex
end
puts Triceratops.classification # => "Big teeth bird!"
Output
Like a Reptile, but like a bird
Big teeth bird!
Big teeth bird!
Big teeth bird!
Global Variables
The first character for global variables is a dollar ($). They can be accessed from anywhere in the program during runtime because of their global scope. Ruby predefines a lot of global variables, frequently with punctuation (such as $_, $!). These unique globals have more evocative, accessible names with the English.rb module. An uninitialized global variable returns nil when referenced.
Code Example:
$total_animals = 0 # Global variable
class Cat
def initialize
$total_animals += 1
end
end
class Dog
def initialize
$total_animals += 1
end
end
bob = Cat.new()
puts $total_animals #=> 1
fred = Dog.new()
puts $total_animals #=> 2
Output
1
2
Variable Assignment
Assignment expressions are used to define variables and assign values to them.
- Simple Assignment: Uses the = operator to assign a value to a variable.
- Parallel Assignment: Enables assigning more than one variable in a single line, which is especially helpful when changing values.
- Abbreviated Assignment: Adds and reassigns by combining an operator with an assignment, like +=.
- Other abbreviated assignment operators include
-=
,*=
,/=
,%=
,**=
,&&=
,||=
,&=
,|=
,^=
,<<=
, and>>=
.
The reference to the object, not the actual object, is copied by Ruby when a variable is assigned to another. Thus, the same object can be referenced by more than one variable. The eval method can be used to dynamically manipulate variables by name; it is frequently used in conjunction with Binding objects to control the scope of evaluation.
You can also read Introduction To Ruby, Why It Is Used, Versions And Set Up
Variable rules
Variable names should always be lowercase, and multiple words that make up a variable name should be split by an underscore. This is known as snake_case.