Variables

From RubySpec

Jump to: navigation, search

Contents

Local Variables

Local variables start with a lower case letter[a-z] or an underscore. Variables are lexically scoped, but only within blocks/closures. All local variables in a non-block scope are at the same level, as in the following example:

a = 1
if true
  a = 2 # reassigns same a
  b = 3 # assigns b for the first time
end
puts b # ok, b is still part of the same scope

Local variables often must be "declared" before they are used in a block. This is generally accomplished by assigning them to some value or to nil

a = nil # "declare" a
b, c = nil # "declare" b and c
1.times {
  a = 1 # assigns same a
  d = 2 # d gets scoped only within this block, since it did not exist previously
}
puts a # => 1
puts d # error...no d variable in this scope

Global Variables

Global variables start with a $ and can then be followed by [a-zA-Z0-9] or an underscore. There are other global 'variables', such as $!, $@, $$, $`, $&, $^, $*, $", $', $_,, $, $; and $:. See the Ruby-Doc page on English.rb for a complete list with descriptions.

Instance Variables

Instance variables start with @ and can then be followed by [a-zA-Z0-9] or an underscore. Must be initialized inside an instance method, otherwise, if initialized outside any method, will become Class Instance Variable.

Class Instance Variables

Class instance variables start with @ and can then be followed by [a-zA-Z0-9] or an underscore. Variables initialized outside any method (but inside the class definition). These variables can be accessed only from class methods and instance methods of this class.

Class Variables

Class variables start with @@ can then be followed by [a-zA-Z0-9] or an underscore

Personal tools