A summary of variable learning in Ruby and a summary of Ruby variable learning

Source: Internet
Author: User

A summary of variable learning in Ruby and a summary of Ruby variable learning

Variables in Ruby are in several forms, including local variables, instance variables, class variables, and global variables. For Beginners, they are often easy to mix up, especially java-like, it is still a headache to understand. After careful identification and learning, we will summarize the differences between these variables and their application scenarios as follows:

I. Naming Method

1. local variables: Start with a lowercase letter or "_", such as a user. The Interpreter starts to exist in the memory only after it is interpreted, A good habit is to use nil for value assignment initialization during variable definition. Otherwise, an error similar to undefined local variable or method 'Z' may occur;
2. instance variables: Start with @, for example, @ user. nil is initialized by default. The "instance" here refers to the class object itself or the class object;
3. class variable: starts with @, for example, @ user. It must be initialized before it can be called. Otherwise, an error similar to uninitializalized class variable @ user in Account may occur;
4. global variables: start with $, for example, $ user. The default value is nil;

II. Scope of action

Local variables: such as user, act only on this class, this method, or this module. Unlike java language habits, variables defined in the class can be called in the class method, the local variables defined in Ruby can only be accessed in the class, but cannot be called in its subclass, method, or internal class. The following is an example code:
Copy codeThe Code is as follows:
Class Account
User = User. new
Def myMethod
Puts user. name # Call error, user undefined
End
End

Instance variables:For example, @ user is a bit similar to the member variables of the POJO class in java. It is randomly accessed in the class and accessed through methods outside the class, it acts within the scope of the instance object or within the scope of the Instance Object of this class (this sentence is a bit difficult, please note that the class object itself [Account, is an object of the Class] and the object [Account. new, is an object of the Account class]), which is two mutually independent domains, the variables defined in the Account cannot be in the Account. and vice versa. See the following sample code:

Copy codeThe Code is as follows:
Class
# Class instance variables can be assigned a value or no value before access. nil is not assigned a value.
@ Alpha = 'this is @ alpha \ 'value! '

Def A. look
Puts "# @ alpha"
End
Def look
Puts "# @ alpha"
End
End

A. look # output: 'This is @ alpha' value! ''
A. new. look # output :''

Let's look at the following code:

Copy codeThe Code is as follows:
Class
# Class instance variables can be assigned a value or no value before access. nil is not assigned a value.
@ Alpha = 'this is @ alpha \ 'value! '

Def A. look
Puts "# @ alpha"
End
Def look
@ Alpha = 'this is @ alpha \ 'value from look! '
Puts "# @ alpha"
End
Def look_again
Puts "# @ alpha"
End
End

A. look # output: 'This is @ alpha' value! ''
A = A. new
A. look # output: 'This is @ alpha' value from look! '
A. look_again # output: 'This is @ alpha' value from look! '

Visible, @ alpha = 'this is @ alpha \ 'value! 'Is the instance variable defined in the class object, @ alpha = 'this is @ alpha \' value from look! 'Is the instance variable defined in the object after class instantiation. In addition, pay attention to the following points when using instance variables:

1. instance variables, whether defined in the class or in the method, belong to the class rather than the method.
2. The instance variable only exists in the instance range and cannot be referenced or assigned a value in the subclass.
3. instance variables are always Private and cannot be exposed to Public. External access is implemented through methods. You can use attr_accessor for simple definition.

Class variables:For example, @ user acts on all the scopes of the class, and all instance objects are shared, including subclass and instance objects. The class variables are declared through Protected, and the following example code is provided:
Copy codeThe Code is as follows:
Class
# Class instance variables can be assigned a value or no value before access. nil is not assigned a value.
@ Alpha = 'this is @ alpha \ 'value! '

Def A. look
Puts "# @ alpha"
End
Def look
Puts "# @ alpha"
End
Def look_again
Puts "# @ alpha"
End
End

Class B <
End

A. look # output: 'This is @ alpha' value! '
B. look # output: 'This is @ alpha' value! '
A = A. new
A. look # output: 'This is @ alpha' value! '
A. look_again # output: 'This is @ alpha' value! '
B = B. new
B. look # output: 'This is @ alpha' value! '
B. look_again # output: 'This is @ alpha' value! '

Global variables:For example, $ user can be used as little as possible to act on the entire program lifecycle and resident memory. Excessive use may cause performance degradation and memory overflow. Ruby has some built-in global variables, making it very convenient to obtain relevant data, for example, $0 indicates the file name of the running application, and '$:' indicates the default file search path; '$' indicates the process id of the ruby program.


In Ruby, what are the differences between instance variables and class variables?

The variable starting with @ is [instance variable], and the instance variable belongs to a specific object.
Class Person
Def initialize (name, gender, age)
@ Name = name
@ Gender = gender
@ Age = age
End
End
In the above example, @ name, @ gender, and @ age are all instance variables. Instance variables can be referenced in class or subclass methods. If you reference an instance variable that has not been initialized, its value is nil.
[Class variable] is shared by all instance objects of a class, and can also be accessed by class methods. The class variable name starts with '@', for example, '@ number '. Unlike global variables and instance variables, class variables must be initialized before use:
Class Person
@ Number = 0 # The initial value must exist before use
Def initialize (name, gender, age)
@ Name = name
@ Gender = gender
@ Age = age
@ Number + = 1
End
End
Class variables are private and cannot be directly accessed outside the class. You can only access them through instance methods and class methods.

In Ruby, how does one define the reference relationship between variables?

Int jimmy; // declare an int Type Variable
String ruby; // string type variable

Jimmy = Console. Read (); // accepts input characters and converts them to int type and returns them to jimmy

Console. Write (jimmy); // output the jimmy Value

Console. WriteLine (jimmy); // output the jimmy value and wrap it
Console. WriteLine (char) jimmy); // output the jimmy value after converting to the bytes type
Ruby = Console. ReadLine (); // enter a string and assign it to ruby.
Console. Write (ruby); // output ruby

Console. WriteLine (ruby); // output the ruby string and wrap it
Console. ReadLine (); // wait for Input

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.