Variable
In the ruby world, there are five types of variables: global variables, local variables, instance variables, constant variables, and pseudo variables.
Common:
Global:
For global use, start with $. Because it is global, the value can be changed in any code example,
It is not recommended to use.
Partial:
It works within a certain range. For example, I = 10, where I is a local variable
Constant:
For example, the circumference rate Pi, but we can assign another value to the PI, which can be changed.
The first letter of a constant must be capitalized. When you try to change the constant value, the interpreter will warn "ex4.rb: 19: Warning: already initialized constant age
"
Pseudo Variable:
These variables, such as false, true, nil, and self, have special meanings. They are read-only and cannot be changed. If you try to change the value, the interpreter reports the error "ex4.rb: 4: Can't assign to False false = 1"
Instance:
Class is used for internal instantiation. Only the instantiated objects can use (BIND) instance variables, and the accessed instance variables use set and get to set and query respectively.
This is detailed in the learning class.
Class variables:
Rarely used.
The following is a code example to explain global local pseudo variables and constants.
|
# coding: utf-8
#! / usr / bin / env ruby
$ GlobalVAR = 1 #Global variable
#false = 1 #Pseudo variable whose value cannot be changed, remove comment will report an error
Age = 15 #constant
def plus (a, b)
# a, b are local variables, the effect is only in the plus method
$ GlobalVAR = $ GlobalVAR +1
puts $ GlobalVAR
return a + b
end
puts plus (5,6)
puts Age
Age = Age + 10 # Change the constant value, the interpreter will warn
puts Age
puts $ GlobalVAR
puts false
|