First, global variables
Global variables are supported in Ruby, and global variables in Ruby are characterized by the following:
1) identifiers are marked with a $ start
2) Global variables can be referenced from anywhere in the program
3) nil.
Let's take a look at the example
class Demo def puts $a end end puts $a # reference undeclared global variable, $a this value is nil demo = Demo.newdemo. print # $a =12demo. print # The output is 12 because then $ A already has a value of
It should be explained that in the actual coding we try not to define global variables, using global variables is a very bad way of programming.
Second, constant
Constants in Ruby must be defined in a class and cannot be defined in a method, and the first letter of a constant identifier must be capitalized.
Example:
class Demo = 3.14 defprint puts Pi end End # Create an object, call the method of the object = Demo.newdemo . Print = 4 # There will be a warning, but there will be no error, and the modification will take effect demo. Print
Note that it is different from other languages. The value of a constant can be modified outside the class (it cannot be modified in the method of the Class), although a warning is reported, but no error occurs.
Ruby Learning: Global Variables and constants