Variables in Ruby

There are few types of variables that can be defined in Ruby

  • Local Variables
  • Global Variables
  • Class Variables
  • Instance Variables
  • Pseudo-Variables
  • Ruby Constants

Let us look into them one by one

Try

Local Variable

Local variable begin with a lowercase letter or an ‘_’. The scope of a local variable can be limited to a class, a module, a function or even a block of code.

All the uninitialized local variables are interpreted as a call to a method that has no arguments. When a value is assigned to such a variable, it is said to have been initialized. These variables exist till the end of the scope is reached.
 

Global Variable

Global Variables are declared with a $ sign. The scope of these variables spans through the entire program. An uninitialised global variable will end up having a nil value.
 

Class Variables

Class variables start with a @@ sign. They need to be initialized before being used. The value of the class variable remains consistent throughout the class. If the value of the class variable changes in an instance, then the value is perceived to be changed in all the other instances.
 

Try

Instance Variables

Instance variables start with an @ sign. These variables will have a nil value if they are not initialized. The scope of these variables is restricted to whatever object self refers to.

Pseudo Variables

They are variables that have the scope and the appearance of a local variable, but cannot be assigned any value.
 

self − The receiver object of the current method.

true − Value representing true.

false − Value representing false.

nil − Value representing undefined.

__FILE__ − The name of the current source file.

__LINE__ − The current line number in the source file.

Assignment Try

Ruby program to use local variable take input from user and print if its odd or even number
=begin
Ruby program to use local variable take input from user and print if its odd or even number

INPUT 
4

OUTPUT
Even Number
=end
# storing the console message in variable
message = "Enter the number"
# printing the msg to the console
puts message
#Reading the input from the console
number = gets
#Here the input from the console is type-casted into integer using to_i
number = number.to_i
if (number%2==0)
  puts "Even Number"
else
  puts "Odd Number"
end

Ruby constants

Ruby constants are defined with an uppercase letter in the beginning. The scope of these constants is dependent on the place they have been defined and initialized at.

One has to be careful while working with constants and take care of the following pointers

  • Constants should not be defined within methods
  • Referencing an uninitialized constant throws an error
  • Assigning a value to an initialized constant shows a warning.