An introduction to Ruby variables that you will regret if you don’t learn it

Hits: 0

Ruby variables

Variables are storage locations that hold any data that can be used by any program.

Ruby supports five types of variables.

  • Usually lowercase letters, starting with an underscore: Variable.
  • $Start: Global variable.
  • @Start: Instance variable (Instance variable).
  • @@Beginning: Class variables are shared throughout the inheritance chain
  • Start with a capital letter: Constant.

With a general understanding of these variables, the five types of variables will be explained in detail below.

Ruby global variables

Global variables start with $. An uninitialized global variable has the value nil , which produces a warning when the -w option is used.

Assigning a value to a global variable changes the global state, so it is not recommended to use global variables.

The following example shows the usage of global variables.

#!/usr/bin/ruby
# -*- coding: UTF-8 -*-

$global_variable = 10 
class  Class1 
  def  print_global 
      puts "Global variables are output in Class1 as #$global_variable" 
  end 
end 
class  Class2 
  def  print_global 
      puts "Global variables are output in Class2 as #$global_variable" 
  end 
end

class1obj = Class1.new
class1obj.print_global
class2obj = Class2.new
class2obj.print_global

Here, $global_variable is the global variable. This will produce the following results:

Note: In Ruby, you can access the value of any variable or constant by preceding the variable or constant with the # character.

The global variable is output as 10 in Class1
The global variable is output as 10 in Class2

Ruby instance variables

Instance variables start with @. Uninitialized instance variables have the value nil , which produces a warning when the -w option is used.

The following example shows the usage of instance variables.

#!/usr/bin/ruby

class Customer
   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
end

# create object 
cust1=Customer.new( "1" , "John" , "Wisdom Apartments, Ludhiya" )
cust2=Customer.new("2", "Poul", "New Empire road, Khandala")

# call method
cust1.display_details()
cust2.display_details()

Here, @cust_id, @cust_name, and @cust_addr are instance variables. This will produce the following results:

Customer id 1
Customer name John
Customer address Wisdom Apartments, Ludhiya
Customer id 2
Customer name Poul
Customer address New Empire road, Khandala

Ruby class variables

Class variables start with @@ and must be initialized before they can be used in method definitions.

Referencing an uninitialized class variable produces an error. A class variable is shared among subclasses or submodules of the class or module in which it is defined.

Overloading class variables produces a warning after using the -w option.

The following example shows the usage of class variables.

#!/usr/bin/ruby

class Customer
   @@no_of_customers=0
   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 object 
cust1=Customer.new( "1" , "John" , "Wisdom Apartments, Ludhiya" )
cust2=Customer.new("2", "Poul", "New Empire road, Khandala")

# call method
cust1.total_no_of_customers()
cust2.total_no_of_customers()

Here, @@no_of_customers is a class variable. This will produce the following results:

Total number of customers: 1
Total number of customers: 2

Ruby local variables

Local variables start with a lowercase letter or underscore _. Local variables are scoped from class, module, def or do to the corresponding end or from the opening brace to the closing brace {}.

When calling an uninitialized local variable, it is interpreted as calling a method with no arguments.

Assignments to uninitialized local variables can also be treated as variable declarations. The variable will exist until the end of the current field. The lifetime of a local variable is determined when Ruby parses the program.

In the above example, the local variables are id, name and addr.

Ruby constants

Constants start with a capital letter. Constants defined inside a class or module can be accessed from within the class or module, and constants defined outside a class or module can be accessed globally.

Constants cannot be defined inside methods. Referencing an uninitialized constant produces an error. Assignment to an already initialized constant produces a warning.

#!/usr/bin/ruby
# -*- coding: UTF-8 -*-

class  Example 
   VAR1 = 100 
   VAR2 = 200 
   def  show 
       puts "The value of the first constant is #{VAR1} " 
       puts "The value of the second constant is #{VAR2} " 
   end 
end

# create object
object=Example.new()
object.show

Here, VAR1 and VAR2 are constants. This will produce the following results:

The value of the first constant is 100
The value of the second constant is 200

Ruby pseudo variables

They are special variables that have the appearance of local variables but behave like constants. You cannot assign any value to these variables.

  • self: The receiver object of the current method.
  • true: represents the value of true.
  • false: represents the value of false.
  • nil: represents the value of undefined.
  • FILE: The name of the current source file.
  • LINE: The number of the current line in the source file.

Leave a Reply

Your email address will not be published.