Ruby Learning: Global Variables and constants

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.