Ruby Study Notes 2-Variables

Source: Internet
Author: User


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


 


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.