w3resource

Ruby Variables, Constants

Ruby Variables

Variable is a symbol or name that stands for a value. Variables locate in memory locations and are used to store values such as numeric values, characters, character strings, or memory addresses so that they can be used in any part of the program.

We have discussed the following types of variables and constants supported by Ruby :

  • Local Variables
  • Instance Variables
  • Class Variables
  • Global Variables
  • Constants

Local Variable:

A local variable name must start with a lowercase letter (a-z) or underscore (_) with the eight-bit set.

Local Variable Scope

A local variable is only accessible from within the block of its initialization. See the following example :

In the following example, there are three local variables called color. One is assigned the value, 'Red' within the ‘main scope’ of the program; two others are assigned integers within the scope of two separate methods. As each local variable has a different scope, the assignments have no affect on the other local variables with the same name in different scopes. We have verified it by calling the methods at the end of the program.:

Example:

color = "Red"
def method1 
color = 192
puts("Color Value in method1 : ",color)
end 

def method2
color = 255
puts("Color Value method2: ",color)
end

method1 
method2  
method1
puts("Color Value outside methods : "+color)

Output:

H:\>ruby abc.rb
Color Value in method1 :
192
Color Value method2:
255
Color Value in method1 :
192
Color Value outside methods : Red

Local Variables and Methods:

In Ruby, local variable names and method names are nearly identical. If you have not assigned to one of these ambiguous names ruby will assume you wish to call a method. Once you have assigned to the name ruby will assume you wish to reference a local variable.

The local variable is created when the parser encounters the assignment, not when the assignment occurs:

a = 0 if false # does not assign to a

p local_variables # prints [:a]

p a # prints nil
def big_calculation
  42 # pretend this takes a long time
end

big_calculation = big_calculation()

Now any reference to big_calculation is considered a local variable and will be cached. To call the method, use self.big_calculation.

You can force a method call by using empty argument parentheses as shown above or by using an explicit receiver like self. Using an explicit receiver may raise a NameError if the method's visibility is not public.

Another commonly confusing case is when using a modifier if:

p a if a = 0.zero?

Rather than printing “true” you receive a NameError, “undefined local variable or method `a'”. Since ruby parses the bare a left of the if first and has not yet seen an assignment to it assumes you wish to call a method. Ruby then sees the assignment to a and will assume you are referencing a local method.

The confusion comes from the out-of-order execution of the expression. First, the local variable is assigned to then you attempt to call a nonexistent method.

Instance Variables:

Instance variables are shared across all methods for the same object. The instance variable name must start with '@' character, otherwise instance variable names follow the rules as a local variable(discussed earlier) name.

Syntax:

@insvar

In the following example, Student.new creates a new object - an instance of the class Student. The instance variables @student_id and @student_name.

class Student
  def initialize(student_id, student_name)
    @student_id = student_id
    @student_name = student_name
  end
  
  def show
    puts "Student Name and ID : "
    puts(@student_id, @student_name)
  end
end
Student.new(1, "Sara").show
Student.new(2, "Raju").show

Output:

Student Name and ID :
1
Sara
Student Name and ID :
2
Raju

Note : An uninitialized instance variable has a value of nil.

Class Variables:

Class variables are shared between a class, its subclasses, and its instances.

A class variable must start with a @@ (two “at” signs). The rest of the name follows the same rules as instance variables.

Syntax:

@@classvar

The following example shows that all classes change the same variable. Class variables behave like global variables which are visible only in the inheritance tree. Because Ruby resolves variables by looking up the inheritance tree first, this can cause problems if two subclasses both add a class variable with the same name.

Example:

class School
@@no_off_students = 650
end

# class V sub-class of School  
class V < School
@@no_off_students = 75
end

# class VI sub-class of School  
class VI < School
@@no_off_students = 80
end


puts School.class_eval("@@no_off_students")
puts V.class_eval("@@no_off_students")
puts VI.class_eval("@@no_off_students")

Output:

80
80
80

Global Variables:

In Ruby a global variables start with a $ (dollar sign). The rest of the name follows the same rules as instance variables. Global variables are accessible everywhere.

Syntax:

$globalvar

Example:

$global = 0

class C
  puts "in a class: #{$global}"

  def my_method
    puts "in a method: #{$global}"

    $global = $global + 1
    $other_global = 3
  end
end

C.new.my_method

puts "at top-level, $global: #{$global}, $other_global: #{$other_global}"

Output:

in a class: 0
in a method: 0
at top-level, $global: 1, $other_global: 3

An uninitialized global variable has a value of nil.

Ruby has some special globals that behave differently depending on context such as the regular expression match variables or that have a side-effect when assigned to. See the global variables documentation for details.

Ruby Constants:

A variable whose name begins with an uppercase letter (A-Z) is a constant. A constant can be reassigned a value after its initialization, but doing so will generate a warning. Every class is a constant.
Trying to access an uninitialized constant raises the NameError exception.

Syntax:

ABCD

Example :

class Student
 NO_Students = 800
end
puts  'No of students in the school : ', Student::NO_Students

Here NO_Students is the constant.

Output:

No of students in the school :
800

Ruby : Pseudo Variables

Name Description
self Execution context of the current method.
nil Expresses nothing. nil also is considered to be false, and every other value is considered to be true in Ruby.
true Expresses true.
false Expresses false.
$1, $2 ... $9 These are contents of capturing groups for regular expression matches. They are local to the current thread and stack frame!

Ruby : Pre-defined Variables

Name Description
$! The exception information message set by the last 'raise' (last exception thrown).
$@ Array of the backtrace of the last exception thrown.
$& The string matched by the last successful pattern match in this scope.
$` The string to the left of the last successful match.
$' The string to the right of the last successful match.
$+ The last group of the last successful match.
$1 to $9 The Nth group of the last successful regexp match.
$~ The information about the last match in the current scope.
$= The flag for case insensitive, nil by default (deprecated).
$/ The input record separator, newline by default.
$\ The output record separator for the print and IO#write. Default is nil.
$, The output field separator for the print and Array#join.
$; The default separator for String#split.
$. The current input line number of the last file that was read.
$< An object that provides access to the concatenation of the contents of all the files given as command-line arguments, or $stdin (in the case where there are no arguments). Read only.
$FILENAME Current input file from $<. Same as $<.filename.
$> The destination of output for Kernel.print and Kernel.printf. The default value is $stdout.
$_ The last input line of the string by gets or readline.
$0 Contains the name of the script being executed. Maybe assignable.
$* Command line arguments given for the script. Also known as ARGV
$$ The process number of the Ruby running this script.
$? The status of the last executed child process.
$: Load path for scripts and binary modules by load or require.
$" The array contains the module names loaded by requiring.
$stderr The current standard error output.
$stdin The current standard input.
$stdout The current standard output.
$-d The status of the -d switch. Assignable.
$-K Character encoding of the source code.
$-v The verbose flag, which is set by the -v switch.
$-a True if option -a ("autosplit" mode) is set. Read-only variable.
$-i If an in-place-edit mode is set, this variable holds the extension, otherwise nil.
$-l True if option -l is set ("line-ending processing" is on). Read-only variable.
$-p True if option -p is set ("loop" mode is on). Read-only variable.
$-w True if option -w is set.

Ruby : Pre-defined Constants

Name Description
__FILE__ Current file.
__LINE__ Current line.
__dir__ Current directory.

Previous: Ruby Style Guide
Next: Ruby Operators Precedence



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/ruby/ruby-variables-constants.php