Ruby variables

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

Ruby supports five types of variables.

  • Generally lowercase letters and underscores start: Variable.
  • $Beginning: Global variable.
  • @At the beginning: Instance variable.
  • @@Beginning: Class variables are shared throughout the inheritance chain
  • Start with a capital letter: Constant.

You already know about these variables in the previous chapters. This chapter will explain the five types of variables in detail for you.

Ruby global variables

Global variables start with $. The value of uninitialized global variables is nil , and a warning will be generated after using the -w option.

Assigning values ?? to global variables will change the global state, so it is not recommended to use global variables.

The following example shows the usage of global variables.

 

#!/usr/bin/ruby

$global_variable = 10
class Class1
   def print_global
      puts "Global variable in Class1 is #$global_variable"
   end
end
class Class2
   def print_global
      puts "Global variable in Class2 is #$global_variable"
   end
end

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

 

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

Note: In Ruby, you can access the value of any variable or constant by placing the # character in front of the variable or constant.

Global variable in Class1 is 10
Global variable in Class2 is 10

Ruby instance variables

Instance variables start with @. The value of uninitialized instance variables is nil , and a warning will be generated after using the -w option.

The following example shows the usage of instance variables.

Examples

#!/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 Objects
cust1 = Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2 = Customer.new("2", "Poul", "New Empire road, Khandala")

# Call Methods
cust1.display_details()
cust2.display_details()

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

 
 
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.

Reference to an uninitialized class variable will generate an error. Class variables can be shared among subclasses or submodules of the class or module that defines it.

After using the -w option, overloading class variables will generate a warning.

The following example shows the usage of class variables.

Examples

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 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:

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

Ruby local variables

Local variables start with a lowercase letter or underscore _. The scope of local variables ranges from class, module, def or do to the corresponding end or from left brace to right brace {}.

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

Assigning to uninitialized local variables can also be regarded as variable declarations. The variable will exist until the end of the current field. The life cycle of local variables is determined when the Ruby resolves the program.

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

 

Ruby constants

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

Constants cannot be defined in methods. Reference to an uninitialized constant will produce an error. Assigning a value to an initialized constant will generate a warning.

Examples

#!/usr/bin/ruby

class Example
   VAR1 = 100
   VAR2 = 200
   def show
      puts "Value of first Constant is #{VAR1}"
      puts "Value of second Constant is #{VAR2}"
   end
end

# Create Objects
object = Example.new()
object.show
 

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

Value of first Constant is 100
Value of 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 values ??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.

Ruby Basic Literals

The rules Ruby uses for literals are simple and intuitive. This section explains all basic Ruby Literals.

Integer Numbers

Ruby supports integer numbers. An integer number can range from -230 to 230-1 or -262 to 262-1. Integers within this range are objects of class Fixnum and integers outside this range are stored in objects of class Bignum.

You write integers using an optional leading sign, an optional base indicator (0 for octal, 0x for hex, or 0b for binary), followed by a string of digits in the appropriate base. Underscore characters are ignored in the digit string.

You can also get the integer value, corresponding to an ASCII character or escape the sequence by preceding it with a question mark.

Example

123                  # Fixnum decimal
1_234                # Fixnum decimal with underline
-500                 # Negative Fixnum
0377                 # octal
0xff                 # hexadecimal
0b1011               # binary
?a                   # character code for 'a'
?\n                  # code for a newline (0x0a)
12345678901234567890 # Bignum

Floating Numbers

Ruby supports floating numbers. They are also numbers but with decimals. Floating-point numbers are objects of class Float and can be any of the following −

Example

123.4                # floating point value
1.0e6                # scientific notation
4E20                 # dot not required
4e+20                # sign before exponential

String Literals

Ruby strings are simply sequences of 8-bit bytes and they are objects of class String. Double-quoted strings allow substitution and backslash notation but single-quoted strings don't allow substitution and allow backslash notation only for \\ and \'

Example

#!/usr/bin/ruby -w

puts 'escape using "\\"';
puts 'That\'s right';

 

This will produce the following result −

escape using "\"
That's right

 

Ruby Arrays

Literals of Ruby Array are created by placing a comma-separated series of object references between the square brackets. A trailing comma is ignored.

Example

#!/usr/bin/ruby

ary = [  "fred", 10, 3.14, "This is a string", "last element", ]
ary.each do |i|
   puts i
end

 

This will produce the following result 

fred
10
3.14
This is a string
last element

 

Ruby Hashes

A literal Ruby Hash is created by placing a list of key/value pairs between braces, with either a comma or the sequence => between the key and the value. A trailing comma is ignored.

Example

#!/usr/bin/ruby

hsh = colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f }
hsh.each do |key, value|
   print key, " is ", value, "\n"
end

This will produce the following result

red is 3840
green is 240
blue is 15

Ruby Ranges

A Range represents an interval which is a set of values with a start and an end. Ranges may be constructed using the s..e and s...e literals, or with Range.new.

Ranges constructed using .. run from the start to the end inclusively. Those created using ... exclude the end value. When used as an iterator, ranges return each value in the sequence.

A range (1..5) means it includes 1, 2, 3, 4, 5 values and a range (1...5) means it includes 1, 2, 3, 4 values.

Example

#!/usr/bin/ruby

(10..15).each do |n| 
   print n, ' ' 
end

This will produce the following result

10 11 12 13 14 15

Subscribe For Daily Updates