Showing posts with label variable. Show all posts
Showing posts with label variable. Show all posts

Tuesday, October 11, 2011

Variables as reference to objects

Variables are used to hold references to objects. As previously mentioned, variables themselves have no type, nor are they objects themselves; they are simply references to objects.
x = "abc"

An exception to this is that small immutable objects of some built-in classes, such as Fixnum, are copied directly into the variables that refer to them. (These objects are no bigger than pointers, and it is more efficient to deal with them in this way.) In this case assignment makes a copy of the object, and the heap is not used.
Variable assignment causes object references to be shared.
y = "abc"
x = y
x # "abc"

After executing x = y, variables x and y both refer to the same object:
x.object_id     # 53732208
y.object_id # 53732208

If the object is mutable, a modification done to one variable will be reflected in the other:
x.gsub!(/a/,"x")
y # "xbc"

Reassigning one of these variables has no effect on the other, however:
# Continuing previous example...
x = "abc"

y # still has value "xbc"

Variables in Ruby

Variables and other identifiers normally start with an alphabetic letter or a special modifier. The basic rules are as follows:
  • Local variables (and pseudovariables such as self and nil) begin with a lowercase letter or an underscore.
  • Global variables begin with a $ (dollar sign).
  • Instance variables (within an object) begin with an @ (at sign).
  • Class variables (within a class) begin with two @ signs.
  • Constants begin with capital letters.
  • For purposes of forming identifiers, the underscore (_) may be used as a lowercase letter.
  • Special variables starting with a dollar sign (such as $1 and $/) are not dealt with here.
Here are some examples of each of these:
  • Local variables alpha, _ident, some_var
  • Pseudovariables self, nil, __FILE__
  • Constants K6chip, Length, LENGTH
  • Instance variables @foobar, @thx1138, @NOT_CONST
  • Class variable @@phydeaux, @@my_var, @@NOT_CONST
  • Global variables $beta, $B12vitamin, $NOT_CONST
There are no declarations of variables in Ruby. It is good practice, however, to assign nil to a variable initially. This certainly does not assign a type to the variable and does not truly initialize it, but it does inform the parser that this is a variable name rather than a method name.