Ruby: Variable

By Xah Lee. Date: .

Variable Name Prefix and Variable Scope

Starting SymbolExplanation
a…z or _lower case = local variable
A…Zupper case = Constant
$global variable
@instance variable (of a class in OOP)
@@class variable (of a class in OOP)
# ruby

xx = 3
p defined?(xx) == "local-variable"

$xx = 4
p defined?($xx) == "global-variable"

# @xx = 5
# p defined?(@xx) == "instance-variable"

# @@xx = 6
# p defined?(@@xx) == "class variable"

Constants starts with a capital letter. This is enforced by Ruby interpreter. However, Ruby actually allows you to redefine a constant. When you do so, it gives a warning.

# ruby

# constant
B2 = 5

# changing constant gives a warning
B2 = 6 # warning: already initialized constant B2

# changing constant still works
p B2 == 6

Predefined Global Variables

Variable NameVariable Value
$0name of the Ruby script file currently executing
$*command line arguments used to invoke the script. (a array)
$$Ruby process ID
$?exit status of last executed child process

There are many more. For complete list, see: Ruby: List of Predefined Global Variables