Ruby: Variable
Variable Name Prefix and Variable Scope
- Ruby has 4 variable scopes: {local, global, instance, class}.
- Variable name's first character determines its scope.
Starting Symbol | Explanation |
---|---|
a…z or _ | lower case = local variable |
A…Z | upper 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 Name | Variable Value |
---|---|
$0 | name 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